In C++, classes can have static and non-static members (variables and functions). They were introduced to support shared data (for all objects of the class) as well as functions that do not require access to the state of a specific instance.
It is important to distinguish between static and non-static members, as they have different lifecycles, scopes, and initialization rules. Common mistakes include: incorrect definitions, simultaneous use of instance and static members, and redefinitions in headers.
Static class variables are declared within the class as static, but must be defined separately outside the class (before C++17). They exist in a single instance. Static functions do not have access to non-static (instance) members without explicit qualification.
Code example:
class Counter { public: static int count; Counter() { ++count; } static void Reset() { count = 0; } }; int Counter::count = 0;
Key features:
Can a static class variable be initialized directly inside the class (before C++17)?
No, before C++17, a static member needs to be defined outside the class. In C++17 and later, inline static allows definition directly inside the class.
// C++17 class Foo { inline static int counter = 0; };
Does a static class function have access to this or non-static members?
No, static members do not have access to non-static members or this, even if instances of the class are created. To access them, you need to explicitly pass the object.
Will a static class member be created for each instance of the class?
No, static members exist in a single instance for the entire class regardless of the number of objects.
A developer declares static int in a class but does not define it outside the class. The linker throws an undefined symbol error, as the static member is not initialized.
Pros:
Cons:
A static member is declared in the class, defined outside the class, and used as a counter for created objects.
Pros:
Cons: