Static Members
Class-level variables and methods
Interview Relevant: Shared state
Static Members
Members shared across all instances of a class.
Code Examples
Static variables and methods in classes.
cpp
1class Counter {
2 static int count; // Declaration
3 int id;
4
5public:
6 Counter() : id(++count) {}
7
8 static int getCount() {
9 return count;
10 // Cannot access non-static members here!
11 }
12
13 int getId() const { return id; }
14};
15
16// Definition (required, usually in .cpp)
17int Counter::count = 0;
18
19// Usage
20Counter c1, c2, c3;
21cout << Counter::getCount(); // 3
22cout << c1.getId(); // 1
23cout << c2.getId(); // 2
24
25// C++17: inline static
26class Modern {
27 inline static int value = 42; // No separate definition needed
28};
29
30// Static const member
31class Config {
32 static const int MAX_SIZE = 100; // OK inline
33 static constexpr double PI = 3.14159; // C++11
34};