Start learning free

LESSON 278 OF 667 · FUNCTIONS & CLASSES

Member Variables in C++

Lesson

TL ; DR:

  • A member variable (or field) is a variable that lives inside a class. Each object of that class has its own copy.


  • Declare member variables under a public: access label so other code can read and write them:

    class Dog {
    public:
        string name;
        int age;
    };
    

  • Access them on an object with the dot operator: dog.name = "Rex";



Full lesson:

Right now your Dog class is just an empty shell — every Dog object you create is identical. We need a way to attach data to each object.

That's what member variables are for. A member variable is a variable that belongs to a class — and each object created from that class gets its own copy of every member.


Declaring member variables

class Dog {
public:
    string name;
    int age;
};
  • public: is an access label — every member declared after it is accessible from outside the class. Without it, members default to private in a class.

  • string name; is a regular variable declaration.


Reading and writing

Dog dog;
dog.name = "Rex";        // write
dog.age = 4;
cout << dog.name << endl;  // read

Each object has its own slot for every member, so two dogs can have different names without interfering.


Your task

Update the Dog class to have two member variables: name (a string) and age (an int) under a public: label. Then in mainFunction, set them on the dog object so the pre-filled cout prints:

Rex is 4 years old
STEP 1 OF 2
    Ctrl + Enter to check