Learn C++
#include "oopbasics/static_members.hpp"

Static Members in C++

//concept

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.

//how it works
1

One shared copy

static int count; exists once for the whole class — every object reads and writes the same variable.

2

Called on the class

Widget::create() invokes a static function with no object; inside, this doesn't exist and instance members are unreachable.

3

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.

4

Count and configure

Increment in constructors for live-instance counts; expose shared constants and factories that logically belong to the type.

//example
#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;
}
Output
2
1alive is defined once outside the class, starting at 0 — the declaration inside only announces it.
2Constructing a and b each increments the same shared counter to 2.
3Widget::alive reads the class-level value directly with no object needed (destruction order would later bring it back down).
//use cases
Live-object counters and shared caches across all instances
Factory methods (Widget::create()) that construct without an existing object
Class-wide constants and configuration every instance shares
Inline static data (C++17) to define shared storage without a .cpp line

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.