Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access derived class static members from inherited base class function in c++

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?

like image 361
Red Needle Avatar asked Nov 17 '25 06:11

Red Needle


1 Answers

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;
    }
};
like image 126
bitmask Avatar answered Nov 18 '25 20:11

bitmask