I was first introduced to keyword static when going over singleton classes and then saw it again when trying to prevent a class from instantiating on the stack.
Now I am trying to simply initialize a static variable, and after many trials I could not seem to do it inside the class unless it was a const. I could not do it in the main() either and the only place I can seem to be able to do it is outside the class & outside main().
When I think about it, it kind of makes sense that initialization is blocked otherwise it may initialize the static member over and over again upon instantiation of each object. Is this set in stone, or is there another way to initialize?
The reason is that variables are normally only allowed be defined once. Class definitions are normally put in header files so if the static variable inside the class definition was a variable definition it would lead to multiple definitions because it would get defined in each translation unit where it is included. That's why it's only a declaration so you can define it outside the class in a .cpp file where it only gets defined once.
That said, C++17 introduced inline variables which, like inline functions, are allowed to be defined multiple times (in different translation units, assuming they are the same). This makes it possible to define static variables directly inside the class definition.
1 2 3 4 5 6
class Test
{
public:
staticinlineint counter = 1;
...
};