St.Antario
St.Antario

Reputation: 27455

Definition of the static data member

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

Upvotes: 2

Views: 619

Answers (2)

user657267
user657267

Reputation: 21040

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.

Upvotes: 2

Xiaotian Pei
Xiaotian Pei

Reputation: 3260

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

const int GamePlayer::NumTurns;

Upvotes: 1

Related Questions