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;insideDog, underpublic:. The definitionint Dog::count = 0;after the class is already provided. - In the constructor, after
this->name = name;, addcount++;. - 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
RexandBuddyand prints the counter; then it createsMax, prints the counter and Max's name, createsLuna, 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;
}
};
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
