2

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

Praetorian
  • 106,671
  • 19
  • 240
  • 328
St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • The body of `foo` is being optimized away. Try printing the address of `a` and you'll run into linker errors. http://coliru.stacked-crooked.com/a/eff67551fb50c778 Or compile your example with `-O0` instead of `-O2` – Praetorian Jun 19 '15 at 05:12
  • http://stackoverflow.com/a/11301299/6610 says some very useful things about this: you have _declaration_, _definition_ and _initialization_. – xtofl Jun 19 '15 at 05:21

2 Answers2

2

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.

user657267
  • 20,568
  • 5
  • 58
  • 77
  • So what did we do by writing `static const int NumTurns = 5`? Looks like we just declare a variable with and initialize it with the value 5. – St.Antario Jun 19 '15 at 04:39
  • @St.Antario Scott Meyers just told you, you declared the member inside the class definition, but that doesn't define it because it's `static`. – user657267 Jun 19 '15 at 04:40
  • I think OP's mixing _initialization_ with _definition_. Cfr. also http://stackoverflow.com/a/11301299/6610 – xtofl Jun 19 '15 at 05:20
1

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

const int GamePlayer::NumTurns;
Xiaotian Pei
  • 3,210
  • 21
  • 40