capypad
0 day streak
cpp / intermediate
Snippet

Static Class Members

Static members are shared by all instances of a class. There is only one copy of a static member, regardless of how many objects are created.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
class Tracker {
public:
static int instanceCount;
Tracker() { instanceCount++; }
};
 
// Definition outside the class
int Tracker::instanceCount = 0;
Breakdown
1
static int instanceCount;
Declares a member that belongs to the class itself rather than a specific object.
2
int Tracker::instanceCount = 0;
Provides the required definition and memory allocation for the static variable.