Static variables are variables that are not tied to a particular instance, rather they are tied to the class. This means all instances share a copy of static member variables.
Considering the following code:
class Point {
public:
static unsigned int counter;
Point(double x, double y) {
++counter;
}
~Point() {
--counter;
}
private:
double x {};
double y {};
};
unsigned int Point::counter {0};
The counter variable is declared as static by preceding it with the static keyword. It is initialized before any instances are created. A static variable cannot be initialized in the header.
Using the {} results in a compiler error. Instead the variable is initialized in a cpp file which must be available for the linker. That’s not strictly true. From C++17 we can use inline to allow the static variable to initialized in the header. We can also mark them as const so the variable can’t be changed. For example:
static inline const double PI {3.14159};
Prior to C++17, only static variables of int and enum types were initializable in the class header, everything else had to initialised in a cpp file.
Static variable initialization order is not guaranteed. This means if we use one static variable to initialize another, you may get crashes due to the order chosen.