Start learning free

LESSON 396 OF 409 · OBJECT-ORIENTED PROGRAMMING

Static Members in C++ in C++

Practice

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

    Static Members in C++

    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