Start learning free

LESSON 178 OF 343 · OBJECT-ORIENTED PROGRAMMING

Class Fields in C++: Declaring and Using Member Variables

Lesson Read the full explanation

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

    C++ · OBJECT-ORIENTED PROGRAMMING

    Class Fields in C++, explained

    What a member variable is

    A member variable, also called a field or data member, is a variable declared inside a class. It stores a piece of data that belongs to an object. Until now, every Dog you could create was identical, because the class had nothing in it. Member variables are how you give each object its own data.

    The important rule is that each object has its own copy of every member. If the class declares name, then rex has a name, luna has a different name, and changing one doesn't touch the other.

    Declaring members

    A member declaration looks like an ordinary variable declaration, written in the class body:

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

    There are two kinds of lines here:

    • public: is an access label. Every member after it can be used from outside the class, until another label appears. Members of a class are private by default, which means only the class's own functions may touch them. Without the label, dog.name in mainFunction would not compile.
    • string name; and int age; are the members themselves: a type, a name and a semicolon.

    Reading and writing members

    Use the dot operator to reach a member of a particular object:

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

    The expression dog.age means the age of this specific dog. With two dogs, a.age and b.age are two separate variables.

    Members start with whatever the type gives them

    Creating an object does not automatically give every member a useful value. What you get depends on the member's type:

    • A string member starts as the empty string, because string is a class with its own constructor.
    • A plain int member of a local object starts with an indeterminate value. Reading it before assigning it is undefined behaviour, and the program may print anything.

    So with the class above, Dog dog; followed directly by cout << dog.age; is a bug, even though it may appear to work and print 0 on some runs. Always give number members a value before reading them. One way is to write a default right in the declaration:

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

    With int age = 0;, every new Dog starts with age 0 unless something sets it otherwise. The next lesson shows constructors, which are the standard way to set up members.

    The lesson's exercise

    The starter Dog class has only the public: label. The task has two steps:

    1. Declare the members under public:: a string called name and an int called age. They need to be public because Solution, a different class, sets them.
    2. In mainFunction, below Dog dog;, assign "Rex" to dog.name and 4 to dog.age. The assignments must come before the cout line, because the output shows whatever the members hold at that moment.

    The program prints:

    Rex is 4 years old

    The solution in C++

    class Dog {
    public:
        string name;
        int age;
    };
    
    class Solution {
    public:
        void mainFunction() {
            Dog dog;
            dog.name = "Rex";
            dog.age = 4;
            cout << dog.name << " is " << dog.age << " years old" << endl;
        }
    };
    

    The string literal "Rex" is converted to a string when it is assigned to dog.name. The order of the two members in the class doesn't matter for this exercise, though it will matter later when constructors initialize them.

    Common mistakes

    • Leaving out public:. The compiler then reports that name is private within this context.
    • Forgetting the semicolon after a member declaration, or after the class itself.
    • Reading a member before it has a value. The int case is the dangerous one, because it compiles without any complaint.
    • Using the class name instead of an object. Dog.name = "Rex"; is an error. A member belongs to an object, so write dog.name.
    • Assigning inside the class body. Statements like name = "Rex"; can't stand directly in a class body. Only declarations, and functions, belong there.
    • Mismatched types. Assigning the text "4" to an int member is an error. Watch the reverse too: dog.name = 4; compiles, because the number is treated as a single character code, and it does not store the text "4".

    Key takeaways

    • A member variable is declared inside a class, and every object gets its own copy.
    • Put members under public: if code outside the class should read and write them.
    • Reach a member with the dot operator: dog.name.
    • A plain int member has no value until you assign one, so initialize it.
    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free