Possible Duplicate:
Overriding static variables when subclassing
I have a set of classes that are all derived from a base class. Any of these derived classes declare the same static variable. It is however specific to each of the derived classes.
Consider the following code.
class Base {
// TODO: somehow declare a "virtual" static variable here?
bool foo(int y) {
return x > y; // error: ‘x’ was not declared in this scope
}
};
class A : public Base {
static int x;
};
class B : public Base {
static int x;
};
class C : public Base {
static int x;
};
int A::x = 1;
int B::x = 3;
int C::x = 5;
int main() {}
In my base class I wanted to implement some logic, that requires the knowledge of the derived-class-specific x. Any of the derived classes has this variable. Therefore I would like to be able to refer to this variable at base class scope.
This wouldn’t be a problem if it were a simple member variable. However, semantically, the variable is indeed not a property of the derived class’ instance, but rather of the derived class itself. Therefore it should be a static variable.
UPDATE I need the class hierarchy to preserve its polymorphic nature. That is, all my derived class’ instances need to be members of a common base class.
Then however, how can I get my hands on this variable from the base class method?
You can use the Curiously recurring template pattern.
Now classes
Derived1andDerived2will each have astatic int xavailable via the intermediate base class! Also,Derived1andDerived2will both share common functionality via the absolute base classBase.Note: The variable declaration uses C++17’s
inline staticmember declaration to avoid the need for a separate template variable definition.