Definition of the static data member

642 views Asked by At

I'm reading Scott Meyers' C++ and come across this example:

class GamePlayer{
private:
    static const int NumTurns = 5;
    int scores[NumTurns];
    // ...
};

What you see above is a declaration for NumTurns, not a definition.

Why not a definition? It looks like we initialize the static data member with 5.

I just don't understand what it means to declare but not define a variable with the value 5. We can take the address of the variable fine.

class A
{
public:
    void foo(){ const int * p = &a; }
private:
    static const int a = 1;
};

int main ()
{
    A a;
    a.foo();
}

DEMO

2

There are 2 answers

3
user657267 On BEST ANSWER

Because it isn't a definition. Static data members must be defined outside the class definition.

[class.static.data] / 2

The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition.

As for taking the address of your static member without actually defining it, it will compile, but it shouldn't link.

0
Xiaotian Pei On

you need to put a definition of NumTurns in source file, like

const int GamePlayer::NumTurns;