#include <iostream> using namespace std;
class P { public: static void f() { cout<<__PRETTY_FUNCTION__<<endl; } virtual void g() {this->f();} virtual P* i(){ cout<<__PRETTY_FUNCTION__<<endl; return this; } };
class C : public P { public: static void f() { cout<<__PRETTY_FUNCTION__<<endl; } virtual void g() {this->f();} virtual P* i(){ cout<<__PRETTY_FUNCTION__<<endl; return this; } };
int main() {
P* i = new C(); i->f(); // static int P::f(); // problem i->g(); // static void C::f() // solution
i->i()->f(); // virtual P* C::i() ; static void P::f() // enigma? }
http://cpptips.hyperformix.com/cpptips/virt_static_memb
What you want is frequently referred to as “virtual static members”, and C++ doesn't have them.
However, it's pretty easy to emulate them.
One way would be to use virtual functions to assign and access the variable.
These would have to be duplicated in each derived class, but this is better than duplicating *all* the member functions that use the member.
Another way would be to have a single virtual function that returns a pointer or reference to the static, and just this one function would have to be duplicated.