Member variables
- C++ course
- Intermediate
- Lesson 2/116
- 5 min
Learn to declare member variables (fields) in a class.
Member variables
Variables declared in a class body are called member variables. They hold the object's data. In a Product class, std::string name; is a member variable.
Member variables take an access modifier: public from anywhere, private only inside the class. For now we use public so we can access them directly from outside. Member names start lowercase: name, price, stock.
Accessing members
You access a public member of an object with a dot: product.name. Assignment works the same way: product.name = "Pen";. You must declare the object first; you cannot access members before that.
A member variable may hold a garbage value at first. So it is good practice to assign values right after creating the object. std::string starts as an empty string by default, but types like int have undefined content until you assign one.
Practice Add member variables to the Product class
Define a Product class. Under public: add std::string name; and int stock; member variables. In main create an instance, set name to "Pen" and print name with std::cout.
Starter code
#include <iostream>
#include <string>
// Define the Product class here
int main() {
// Create a Product instance, set name and print it
return 0;
}Sample solution
#include <iostream>
#include <string>
class Product {
public:
std::string name;
int stock;
};
int main() {
Product product;
product.name = "Pen";
std::cout << product.name;
return 0;
}Expected output
Pen
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the member declaration
class Product { public: std::string ____; };
class Product { public: std::string name; };
Explanation: Members start with lowercase: name.
2 How do you access product.price?
Product product;- product.price Correct answer
- product->price
- product::price
- product#price
Explanation: The dot accesses a member of a stack object.
3 Match each declaration to its type
| Term | Meaning |
|---|---|
std::string name; |
Member variable |
class Product { }; |
Class definition |
Product product; |
Instance creation |
product.name |
Member access |