Search code examples
c++oopinitializationstatic-initialization

Why should I not initialize static variable in header?


So, let's say I have a header like this:

#ifndef BASECLASS_H
#define BASECLASS_H

class BaseClass
{
    public:
        static int getX(){return x;}
    private:
        static int x;
};

int BaseClass::x = 10;

#endif

I have heard many times that I should not initialise static variables inside a header, but rather in cpp. But as there are guards, there should be only one copy of BaseClass::x. So I kinda do not understand why I should put

int BaseClass::x = 10; 

in cpp.


Solution

  • If you do it in the header, you'll get multiple definition errors as soon as you include it from more than one CPP file. You're really telling the compiler two things when you declare

    int BaseClass::x = 10;
    

    First, you're defining the symbol BaseClass::x; second you're telling it you want it to have the initial value of 10. According to the One Definition Rule this can only happen once in your program.