I have a base class with a static member and a non static function that returns the value of said static member. I also have a derived class that inherits the base class, but assigns an alternate value to the inherited static member.
class Parent
{
protected:
static const int foo = 0;
public:
int GetFoo()
{
return foo;
}
};
class Child : Parent
{
protected:
static const int foo = 1;
};
If I call the inherited getter function on an instance of the derived class, I would expect it to return the value of the static member of the derived class (1). However, it actually returns the value of the static member on the base class instead (0).
int main(int argc, char* argv[])
{
Child child();
std::cout << child.GetFoo();
}
The output is 0
Why was my initial understanding of this interaction incorrect, and how would I attain my expected behavior wherein calling the getter on an instance of the derived class would return the static member of the derived class?
Because member variables are not virtual. You have shadowed Parent::foo within the context of Child but GetFoo() is a member of Parent. If you really need this behaviour you need to pay for the cost of indirection somehow. For example:
class Parent
{
protected:
virtual int foo() {
return 0;
}
public:
int GetFoo()
{
return foo();
}
};
class Child : Parent
{
protected:
virtual int foo() override {
return 1;
}
};
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