Object-Oriented Programming
Static Members
Class-level variables and methods shared across all instances
Interview: Shared state, singleton pattern, and class-level counters are common interview topics
Static Members
Static members belong to the class itself, not to any particular instance. There is exactly one copy of a static member variable, shared across all objects of the class. Static member functions can be called without an object and can only access other static members (they have no this pointer).
Static Variables
Static data members are declared inside the class but defined outside (in the .cpp file). The out-of-class definition is required because the class declaration is just a declaration — the definition provides storage. Exception: inline static (C++17) and static constexpr can be defined inline in the class body.
Static Methods
Static methods can be called as ClassName::method() or via an object (though the former is preferred for clarity). They cannot access non-static members because there is no object (and thus no this). Common uses: factory functions, utility methods, singleton accessors, and class-level counters.
Initialization Order Warning
The initialization order of static variables across translation units is unspecified (the static initialization order fiasco). If a static member depends on another static variable in a different file, use function-local statics (initialized on first call) to ensure safe ordering.
Interview Corner
Q: How do you implement the Singleton pattern using static members?
A: Meyers Singleton: static T& getInstance() { static T instance; return instance; }. The function-local static is initialized on first call (thread-safe since C++11) and lives until program exit. This avoids the static initialization order fiasco — the singleton is created when first needed, not at program startup.
Q: Why can't a static method access non-static members?
A: Non-static members belong to a specific instance — accessing them requires knowing which object. Static methods have no this pointer (no associated object), so they don't know which instance's members to access. To access non-static members, a static method must receive an object reference/pointer as a parameter.
Common Pitfalls
- Forgetting the out-of-class definition: Declaring a non-inline static member in the class body without defining it in a .cpp file causes a linker error.
- Overusing static: Excessive static state creates hidden global dependencies, making code hard to test and parallelize. Prefer dependency injection over global static state.
Best Practices
- Use
inline static(C++17) for static member variables initialized in the class body — no separate .cpp definition needed. - Prefer
static constexprfor compile-time constants that belong to a class rather than free constants.