C++
Static member variables
Learn that static member variables are shared at the class level.
static member variables
A static member variable is shared among all instances of a class. Each instance accesses the same single copy instead of its own.
In a Player class, static int count; tracks the total number of players. The static member is declared inside the class body with the static keyword. Its definition, however, goes outside the class: int Player::count = 0;. This separation ensures a single copy exists in memory. Static members can be accessed without an object as Player::count.
Accessing static members
A static member can be accessed through an instance (player.count) or through the class name (Player::count). The class name access is preferred, because it works even without an instance.
Recommended approach: Player::count. This emphasizes that the member is shared across all instances. The :: symbol is the scope resolution operator; it lets you reach class members from outside. By doing count++ in the constructor, you increment the counter for each new object.
Exercise Add a static counter to the Player class
Define a Player class. Under public: add static int count;. Increment count++ in the constructor. Outside the class write int Player::count = 0;. In main create two Player objects and print Player::count with std::cout.
Show example solution
#include <iostream>
class Player {
public:
static int count;
Player() { count++; }
};
int Player::count = 0;
int main() {
Player p1;
Player p2;
std::cout << Player::count;
return 0;
}
Test yourself
-
Where is a static member definition written?
class Player { static int count; };
- Inside the class body
- Inside the constructor
- Inside the main function
- Outside the class as Player::count
Show answer
Outside the class as Player::count — A static member is defined outside the class as Player::count.
-
Complete the static member declaration
class Player { public: static int ____; };
Show answer
class Player { public: static int count; };
-
Match each piece to its role
- static int count;
- Declaration
- int Player::count = 0;
- Definition
- Player::count
- Access
- count++
- Increment
Next lesson: Static methods