What is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors:
class foo
{
For future viewers of this question, I want to point out that you should avoid what monkey0506 is suggesting.
Header files are for declarations.
Header files get compiled once for every .cpp
file that directly or indirectly #includes
them, and code outside of any function is run at program initialization, before main()
.
By putting: foo::i = VALUE;
into the header, foo:i
will be assigned the value VALUE
(whatever that is) for every .cpp
file, and these assignments will happen in an indeterminate order (determined by the linker) before main()
is run.
What if we #define VALUE
to be a different number in one of our .cpp
files? It will compile fine and we will have no way of knowing which one wins until we run the program.
Never put executed code into a header for the same reason that you never #include
a .cpp
file.
include guards (which I agree you should always use) protect you from something different: the same header being indirectly #include
d multiple times while compiling a single .cpp
file