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 object3 static int count; // The constructor increments the shared count each time an object is created4 Counter() { count++; }5};6 // Define the static member outside the class and start it at 07int Counter::count = 0;8 // Create three objects: the constructor runs three times9Counter a, b, c;// Access the static member through the class name: prints Total: 310cout << "Total: " << Counter::count << endl;Output
Total: 3
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