Static Members in C++
static members belong to the class itself, not to any instance: one shared static data member exists no matter how many objects are created, and static member functions run without an object (so they have no this and can't touch non-static members). Access them as ClassName::member from anywhere visibility allows.
Classic uses are instance counters, shared configuration, and factory functions. Static data needs exactly one out-of-class definition (or inline initialization since C++17) — declaring it inside the class alone doesn't allocate storage.
One shared copy
static int count; exists once for the whole class — every object reads and writes the same variable.
Called on the class
Widget::create() invokes a static function with no object; inside, this doesn't exist and instance members are unreachable.
Define storage once
Static data declared in-class must be defined in exactly one .cpp (int Widget::count = 0;) — or declared inline (C++17) to skip the ritual.
Count and configure
Increment in constructors for live-instance counts; expose shared constants and factories that logically belong to the type.
#include <iostream> class Widget {public: static int alive; Widget() { ++alive; } ~Widget() { --alive; }};int Widget::alive = 0; int main() { Widget a, b; std::cout << Widget::alive << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.