From what I have understood, the reason you initialize a static member in a .cpp file and not in a .h is so there’s no risk to get several instances of the member.Take this example then:
//Foo.h
#ifndef FOO_H
#define FOO_H
class Foo{
static int a;
};
int Foo::a = 95;
#endif
The preprocessor directives make sure that this .h file is only compiled once, which ensures there is only one instance of the static member. Is this possible to do instead of initiate the static member in a .cpp file?
Consider having two source code files,
a.cppandb.cpp, that both include the header. Since they’re compiled independently of each other, the header guard will not work, you will end up with two object filesa.oandb.othat both defineFoo:a. Trying to link them together will fail.