capypad
0 day streak
cpp / beginner
Snippet

Static Class Members

Static members belong to the class itself rather than to any individual object. All objects of the class share the same static variable. When a new object is created, the constructor increments the counter. Static functions can access static members without needing an object. Use Counter::count to access the shared variable directly, or Counter::getCount() to use the static method. This pattern is useful for tracking how many objects of a class have been created.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
 
class Counter {
public:
static int count;
Counter() {
count++;
}
static int getCount() {
return count;
}
};
 
int Counter::count = 0;
 
 
int main() {
Counter c1;
Counter c2;
Counter c3;
std::cout << "Objects created: " << Counter::getCount() << std::endl;
return 0;
}
Breakdown
1
static int count;
Declares a static member variable shared by all instances
2
Counter() { count++; }
Constructor increments count each time an object is created
3
static int getCount() { ... }
Static function that returns the shared counter value
4
int Counter::count = 0;
Definition and initialization of static member outside class
5
Counter::getCount()
Calling static method using class name instead of object