Why can't I call protected virtual base class function in the derived class overridden function?

491 views Asked by At
class Base
{
protected:
    virtual void show()
    {
        // Do some stuff.
    }
};

class Derived : public Base
{
protected:
    virtual void show()
    {
        // Do some stuff.
    }
};

class Derived_2 : public Derived
{
protected:
    virtual void show()
    {
        this->show();    // error: Base::show() is in accessible
        show();          // error: Base::show() is in accessible
        Derived::show(); // error: Base::show() is in accessible
    }
};

In above case calling virtual base class function (overridden in derived classes) gives an error.

2

There are 2 answers

0
Serge Ballesta On BEST ANSWER

The only error I can find, is that you call show from itsel leading to infinite recursion and ending in a stack overflow error.

But this code compiles and run without even a warning :

class Derived_2 : public Derived
{
public:
    virtual void show()
    {
        //this->show();    // infinite recursion => stack overflow
        Base::show();    // ok calls show() from Base
        Derived::show();    // ok calls show() from Derived
        std::cout << "Derived2" << std::endl;
    }
};

(I declared it public to call it directly in my test)

0
VP. On

If I understand you correct and you want to call Base::show() then you may do that by with:

Derived::Base::show(); or just Base::show();

But if you just want to call super class's method you have a correct code.