1) I have a based class with a static data member, and I have a derived class from this based class. During linking, I got a “undefined reference” to this static data member. Why?
2) How can I work around this so the derived class can access to this static data member?
The problem might be because you are not instantiating the static member.
1 2 3 4 5 6
// parent.h
class Parent
{
public:
staticint member;
};
1 2 3 4 5 6
// parnet.cpp
#include "parent.h"
int Parent::member = 0; // <- must have this line to instantiate it
// don't put this line in the header, it must be in a cpp file.
After that, derived classes should be able to access it no problem.
I tried what you suggested, it does not work still. Perhaps I should be more specific. Sorry.
1) Both based and derived class are in the same "hpp" file. And my "cpp" instantiates from the derived class.
2) Without "cpp" instantiates from the derived class. Compilation and linking were OK. Once I instantiates the object from derived class. I was getting this error (undefined reference).