static variable inheritance?

Is there a way to share one static variable amongst all the classes derived from a base class?

The following is my attempt, but the compiler or linker gets an error.
The code compiles if the last line is commented.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// inherited Static variable
#include <iostream>
using namespace std;

class Base
{
	private:
		static int 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
Do you want a hint or the answer?

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:
    static int layer;
    //
};

int Base::layer = 0; // <-- this

int main()
{
    //
}
You can put this :

private:

static int layer;

like:

protected:

static int layer;


Protected: allows subclasess access to private members but only inner the subclass
Topic archived. No new replies allowed.