// inherited Static variable
#include <iostream>
usingnamespace std;
class Base
{
private:
staticint layer;
public:
int getLayer() { return layer; }
};
class Child: public Base
{
};
int main()
{
Child c;
cout << c.getLayer(); // undefined reference to `Base::layer'
// collect2.exe: error: ld returned 1 exit status
}
>g++ temp6.cpp
C:\Users\wolf\AppData\Local\Temp\cc1KGh28.o:temp6.cpp:(.text$_ZN4Base8getLayerEv
[__ZN4Base8getLayerEv]+0xa): undefined reference to `Base::layer'
collect2.exe: error: ld returned 1 exit status
Hint:
One line 19, change c to be an instance of Base (ie, change that line to Base c;). Does it work now? My guess, no. This means that the issue lies not with inheritance but with your use of static variables.
Answer:
You don't initialize Base::layer. Just after the class definition (~line 12 or so), initialize Base::layer:
1 2 3 4 5 6 7 8 9 10 11 12 13
class Base
{
private:
staticint layer;
//
};
int Base::layer = 0; // <-- this
int main()
{
//
}