capypad
0 day streak
cpp / beginner
Snippet

Static Members: Sharing Data Across Objects

Static members belong to the class itself, not to individual objects. This means all objects share the same variable. In this example, totalObjects tracks how many Counter objects have been created - it increases every time a new Counter is made. You can access static members using ClassName::member without creating any objects.

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
28
29
30
#include <iostream>
#include <string>
using namespace std;
 
class Counter {
public:
static int totalObjects;
string name;
Counter(string n) {
name = n;
totalObjects++;
}
void showCount() {
cout << name << " created. Total: " << totalObjects << endl;
}
};
 
int Counter::totalObjects = 0;
 
int main() {
Counter a("Object A");
Counter b("Object B");
Counter c("Object C");
a.showCount();
b.showCount();
cout << "All objects created: " << Counter::totalObjects << endl;
return 0;
}
Breakdown
1
static int totalObjects;
Declaration of static member - shared across all instances
2
int Counter::totalObjects = 0;
Definition outside class - must be defined once globally
3
totalObjects++;
Increments shared counter every time constructor runs
4
Counter::totalObjects
Access static member through class name, no object needed