Skip to content
AgileLogics
3 min read

Static Members

Prerequisites: The this pointer

A static member belongs to the class itself, shared by every instance — exactly the same idea as Java's static fields.

class Counter {
public:
    static int totalCreated;

    Counter() {
        totalCreated++;
    }
};

int Counter::totalCreated = 0; // defined once, outside the class

Counter a, b, c;
std::cout << Counter::totalCreated << std::endl; // 3

Common mistakes

  • Declaring a static member inside the class but forgetting the separate definition outside it (int Counter::totalCreated = 0;) — without it, the linker reports an undefined reference.