Static member variables
- C++ course
- Intermediate
- Lesson 30/116
- 5 min
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.
Practice 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.
Starter code
#include <iostream>
// Define the Player class here
int main() {
// Create two Players and print the count
return 0;
}Sample 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;
}Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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 Correct answer
Explanation: A static member is defined outside the class as Player::count.
2 Complete the static member declaration
class Player { public: static int ____; };
class Player { public: static int count; };
Explanation: Member variables start lowercase: count.
3 Match each piece to its role
| Term | Meaning |
|---|---|
static int count; |
Declaration |
int Player::count = 0; |
Definition |
Player::count |
Access |
count++ |
Increment |