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?
Only one copy of a static member exists, regardless of how many instances of the class are created.
When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present.
Yes it is. Each of your b variables is private to the function in which they are declared. Show activity on this post. b in func and b in main are two different variables, they are not related, and their scope is inside each function that they are in.
So yes, you need to declare a new static variable for each subclass.
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;
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With