Static and Inline in C++
static and inline within classes
-
staticvariables in a class make them shared across all instances of that class. -
staticvariables are declared inside the class but defined separately.
The linestatic int x;only tells the compiler that such a variable exists somewhere, but no storage is yet allocated.
Using it before definition leads to a linker error — “undefined reference tox” — meaning that while the compiler knows the name, no memory exists for it.- The strength of
staticis persistence. Astaticvariable inside a function retains its value between calls; it isn’t destroyed when the function exits. - A
staticmember function can be called without creating an object. It can only access otherstaticmembers of the class. - At global or namespace scope, marking a function
staticgives it internal linkage, restricting visibility to that translation unit.
- The strength of
-
In the case of a resource loader like
{cpp}loadTextures(), making itstaticallows it to be called independently of any object.
A line like{cpp}Image gun_img = LoadImage();inside that function would normally create a local variable.
Declaring it as{cpp}inline static Image gun_img;makes it a single, persistent variable belonging to the class itself — not recreated on each call. -
The
{cpp}inlinekeyword, especially since C++17, allows merging the declaration and definition of{cpp}staticdata members directly in the class.- It also tells the compiler and linker to relax the One Definition Rule (ODR): multiple identical definitions across translation units are fine, only one will be kept.