⚙️ C++ Intermediate

What are static members in C++?

Answer

Static members belong to the class itself rather than any individual object. Shared by all instances — exists independently of any object creation. Static data member: class Counter { static int count; // Declaration public: Counter() { ++count; } ~Counter() { --count; } static int getCount() { return count; } }; int Counter::count = 0; // Definition and initialization (outside class, in .cpp) Counter c1, c2, c3; std::cout << Counter::getCount(); // 3 -- class-level access. Inline static member (C++17): class Config { public: inline static const std::string VERSION = "1.0"; // No separate .cpp definition needed inline static int maxRetries = 3; };. Static member functions: can be called without an object; no this pointer (can only access static members directly): class Math { public: static double pi() { return 3.14159265358979; } static int abs(int x) { return x < 0 ? -x : x; } }; double p = Math::pi(); // Called on class, not object. Singleton pattern (common static use): class Database { static Database* instance; Database() {} // Private constructor public: static Database& getInstance() { static Database inst; // Thread-safe since C++11 (magic statics) return inst; } };. Static local variables: initialized once on first call, persists for program lifetime — different from class-level statics: int generateId() { static int id = 0; // Initialized once return ++id; // Returns 1, 2, 3, ... each call }. Key uses: shared counters, caches, singletons, factory methods, constants, utility functions that don't need object state.