C++: Counting objects with static members

Complete the class Counter with two static members: created (how many Counter objects were ever made) and alive (how many exist now). main makes n objects inside a loop, each dying at the end of its turn, then two more, and prints both counts.

What to build

A Counter class that keeps two static counts.

Requirements

  • Declare created and alive as static members and define them outside the class.
  • Add to both in the constructor.
  • Take one from alive in the destructor.

Input

One number n (0 ≤ n ≤ 1000).

Output

created C alive A

Constraints

0 ≤ n ≤ 1000.

Example

Input:

3

Output:

created 5 alive 2

Why it works

A static member is shared by all the objects, so every constructor and destructor updates the same two counts.

Examples

Example 1 · Input
3
Expected output
created 5 alive 2
Example 2 · Input
0
Expected output
created 2 alive 2

Hints

Hint 1

static int created, alive; are shared by all Counter objects; define them outside the class.

Hint 2

The constructor adds one to both; the destructor takes one from alive.

Hint 3

Objects made inside the loop die at the end of each turn.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;

class Counter {
public:
    static int created;
    static int alive;
    Counter() {
        created++;
        alive++;
    }
    ~Counter() {
        alive--;
    }
};

int Counter::created = 0;
int Counter::alive = 0;

int main() {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
        Counter temp;
    }
    Counter a, b;
    cout << "created " << Counter::created << " alive " << Counter::alive << endl;
    return 0;
}

Lesson: Static and const members →