static variable for each derived class
c++, oop, static
Solution
You can use the Curiously recurring template pattern.
// This is the real base class, preserving the polymorphic structure
class Base
{
};
// This is an intermediate base class to define the static variable
template<class Derived>
class BaseX : public Base
{
// The example function in the original question
bool foo(int y)
{
return x > y;
}
inline static int x;
};
class Derived1 : public BaseX<Derived1>
{
};
class Derived2 : public BaseX<Derived2>
{
};
Now classes `Derived1` and `Derived2` will each have a `static int x` available via the intermediate base class! Also, `Derived1` and `Derived2` will both share common functionality via the absolute base class `Base`. Note: The variable declaration uses C++17's `inline static` member declaration to avoid the need for a separate template variable definition.
Problem
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?