Applying static to ordinary variables
It changes the variable’s storage area and lifetime: the variable lives in static storage, its space is allocated before main runs, and it is initialised with the given initial value — or with the default value if none is given.
An ordinary variable gets space on the stack when execution reaches its definition, and that space is released when the function returns. Marking it static lets the value inside the function survive until the next call.
A static local variable is initialised only once, and its lifetime is extended until the program ends.
| |
Applying static to ordinary functions
It limits the function’s scope: the function can only be used inside the file that defines it. In a project with several people, static keeps your helper from colliding with a same-named function in someone else’s namespace.
Applying static to member variables
It makes every object share one copy of the variable, and the member can be accessed without creating an object.
C++ needs a data object that serves the whole class; that is what a static data member is for.
If every object of a class needs a value, marking it static means you change the value once and all objects see the new value.
Applying static to member functions
It lets the function be called without creating an object, but a static member function cannot access non-static members.
static and const
static const is equivalent to const static; for member variables, read the two together.
A member function cannot be both const and static — the two meanings contradict each other.