Static member in C++

Level 4155 keystrokes

Counts how many Counter objects are created with a static member that all instances share, then prints Total: 3.

C++ code

1class Counter {
2public:
// One count shared by the whole class, not one per object
3 static int count;
// The constructor increments the shared count each time an object is created
4 Counter() { count++; }
5};
6
// Define the static member outside the class and start it at 0
7int Counter::count = 0;
8
// Create three objects: the constructor runs three times
9Counter a, b, c;
// Access the static member through the class name: prints Total: 3
10cout << "Total: " << Counter::count << endl;

Output

Total: 3
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • ;× 6
  • :× 6
  • <× 6
  • ,× 2
  • "× 2
  • {× 2
  • }× 2
  • +× 2
  • (× 1
  • )× 1

More C++ examples at level 4

← C++ typing practice