0

I could not understand why when declaration a static variable causes a external symbol error. Who can describe the differences between below cases?

1) OK

class TrainComposition
{
public:
    int wagons;
    ...
}

2) Error (unresolved external symbol)

class TrainComposition
{
public:
    static int wagons;
    ...
}

3) Error (unresolved external symbol)

class TrainComposition
{
 static int wagons; 
 public:
    ...
}
Sunny Lei
  • 181
  • 1
  • 3
  • 15
  • You should initialize that static variable in global scope – Asesh Jun 23 '17 at 04:07
  • 1
    Possible duplicate of [Unresolved external symbol on static class members](https://stackoverflow.com/questions/195207/unresolved-external-symbol-on-static-class-members) – Asesh Jun 23 '17 at 04:08

1 Answers1

0

2) and 3) are of course the same, the visibility does not change anything on the problem.

You declare your variable, but you don't define it. In other words, in your .cpp file you should add

int TrainComposition::wagons = 0;

This is most often not necessary for static members that are const, but sometimes even then.

Rene
  • 2,466
  • 1
  • 12
  • 18