Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I not initialize static variable in header? [duplicate]

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.

like image 524
user3496846 Avatar asked Apr 04 '14 17:04

user3496846


1 Answers

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.

like image 103
Nathan Monteleone Avatar answered Oct 05 '22 12:10

Nathan Monteleone