Search code examples
c++inheritancevirtual

Access overriden parent virtual method in C++


In the following code, how can I access Base::g() from pBase? (and still get "pBase->g();" to work as it does below)

#include <iostream>
using namespace std;

class Base
{
    public:
    virtual void f(){ cout << "Base::f()" << endl; }
    virtual void g(){ cout << "Base::g()" << endl; }
    void h(){ cout << "Base::h()" << endl; }
};

class Derived : public Base
{
    public:
    void f(){ cout << "Derived::f()" << endl; }
    virtual void g(){ cout << "Derived::g()" << endl; }
    void h(){ cout << "Derived::h()" << endl; }
};

int main()
{
    Base *pBase = new Derived;
    pBase->f();
    pBase->g();
    pBase->h();

    Derived *pDerived = new Derived;
    pDerived->f();
    pDerived->g();
    pDerived->h(); 
    return 0;
}

Output is:

Derived::f()
Derived::g()
Base::h()
Derived::f()
Derived::g()
Derived::h()

Also, is Derived::f() exactly the same as Derived::g()? (ie. automatically defined as virtual?)


Solution

    1. Use pBase->Base::g(); to force the call of g in Base.

    2. Yes, Derived::f is virtual. I personally find the re-emphasising of virtual to be in poor taste. Since C++11, you can use the override specifier on overridden functions, and then a compiler issues a diagnostic if virtual is dropped from the base class.