Start learning free

LESSON 29 OF 69 · OBJECT-ORIENTED PROGRAMMING

Static Members in C++: A Shared Counter

Practice Read the full explanation

TL;DR:

A static member is declared with the static keyword inside the class. There is one copy shared by every Dog. C++ also needs one definition outside the class, int Dog::count = 0;, and the starter already contains it. From outside you reach it as Dog::count.

You start with:

class Dog {
public:
    string name;
    Dog(string name) {
        this->name = name;
    }
};

int Dog::count = 0;

Your task: count how many Dog objects have been created, with one counter shared by all of them.

  • Declare static int count; inside Dog, under public:. The definition int Dog::count = 0; after the class is already provided.
  • In the constructor, after this->name = name;, add count++;.
  • The counter starts at 0 before any dog exists, and goes up by exactly 1 for every dog created, whatever its name.
  • The program that is already in the editor creates Rex and Buddy and prints the counter; then it creates Max, prints the counter and Max's name, creates Luna, and prints the counter once more. Do not change those lines.

Expected output:

2
3
Max
4

Read the counter with Dog::count.

class Dog {
public:
    static int count;

    string name;
    Dog(string name) {
        this->name = name;
        count++;
    }
};

int Dog::count = 0;

class Solution {
public:
    void mainFunction() {
        Dog rex("Rex");
        Dog buddy("Buddy");
        cout << Dog::count << endl;
        Dog third("Max");
        cout << Dog::count << endl;
        cout << third.name << endl;
        Dog fourth("Luna");
        cout << Dog::count << endl;
    }
};

STEP 1 OF 2
    Ctrl + Enter to check

    C++ · OBJECT-ORIENTED PROGRAMMING

    Static Members in C++, explained

    Problem overview

    The starter code has a class Dog with a name, a constructor, and a line after the class, int Dog::count = 0;. The task is to count how many Dog objects have been created, using one counter shared by all of them. The program in the editor creates Rex and Buddy and prints the counter, creates Max and prints the counter and the name, then creates Luna and prints the counter again. Its output must be:

    2
    3
    Max
    4
    

    You write two small things: declare static int count; inside the class, and add count++; to the constructor. The lines in mainFunction stay as they are.

    Approach

    An ordinary member variable such as name belongs to one object: every Dog has its own. A counter of dogs can't live in one dog, because it describes all of them. A static member belongs to the class itself. There is one copy, whatever the number of objects, and every dog sees the same value.

    The constructor runs exactly once for each new dog, which makes it the right place to count. Adding 1 to the shared counter there means the counter grows by one per dog, whatever the name, and starts from the value in its definition: 0.

    From outside the class you reach the counter through the class name, Dog::count. That is how mainFunction prints it, and it works before any dog exists too.

    Step by step

    1. Declare the counter inside Dog, under public:, as static int count;. The keyword static makes it a single shared variable. It is public so that mainFunction can read it as Dog::count.
    2. Add 1 to count at the end of the constructor. Inside a member function you can write count without a prefix, and the line goes after this->name = name;, so it runs for every dog created.

    The line int Dog::count = 0; after the class is already in the starter. Do not remove it.

    The solution in C++

    class Dog {
    public:
        static int count;
    
        string name;
        Dog(string name) {
            this->name = name;
            count++;
        }
    };
    
    int Dog::count = 0;
    
    class Solution {
    public:
        void mainFunction() {
            Dog rex("Rex");
            Dog buddy("Buddy");
            cout << Dog::count << endl;
            Dog third("Max");
            cout << Dog::count << endl;
            cout << third.name << endl;
            Dog fourth("Luna");
            cout << Dog::count << endl;
        }
    };
    

    Reading the output: after Rex and Buddy the counter is 2, after Max it is 3 and Max's name is printed, and after Luna it is 4.

    Why two places?

    The declaration inside the class tells the compiler that Dog has a static member called count. It does not create the variable. The definition int Dog::count = 0;, which appears once outside the class, creates it and gives it its starting value. The Dog:: prefix says which class the name belongs to.

    Leave out the definition and the code compiles, but linking fails with a message ending in undefined reference to `Dog::count'. Leave out the declaration and the compiler reports 'count' was not declared in this scope in the constructor, then 'int Dog::count' is not a static data member of 'class Dog' at the definition.

    Since C++17 there is a shorter form: inline static int count = 0; inside the class declares and defines the variable together, with no line outside. A class written that way and used to create two objects reports a count of 2, like the lesson's version. The lesson uses the classic two-part form, which you will see in a lot of existing code.

    What static members do and don't do

    • One value, many ways to read it. Dog::count and someDog.count are the same variable. The first form is clearer, because it shows that the value belongs to the class.
    • Only constructors that run are counted. The counter goes up in the constructor that takes a string. A copy such as Dog b = a; uses the compiler-made copy constructor, which has no count++, so it does not raise the counter. A class that must count copies needs its own copy constructor.
    • The counter never goes down by itself. A dog that goes out of scope leaves the counter unchanged. The number counts dogs created, which is what the task asks for, not dogs currently alive. To count live objects you would also subtract in a destructor.
    • The starting value comes from the definition. It is set once, before main runs, so the first dog sees 0 and leaves 1.

    Common mistakes

    • Making it a normal member. Without static, every dog would have its own count, and the statement Dog::count would not compile.
    • Counting in the wrong place. Putting count++ in mainFunction after each dog works only until you create a dog somewhere else. The constructor counts every dog automatically.
    • Setting the value in the constructor. Writing count = 1; there resets the counter for every new dog instead of increasing it.
    • Changing the printing lines. They are part of what the lesson's tests check.

    Key takeaways

    • A static data member is one variable shared by all objects of the class.
    • Declare it in the class and define it once outside, as int Dog::count = 0; (or use inline static in C++17).
    • Reach it with ClassName::member from outside, or by its plain name inside member functions.
    • A constructor is the natural place to count objects, and it counts only the constructors that run.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free