Search code examples
c++usingoverriding

Base class method alias


Let's consider the following code:

#include <iostream>

class Base
{
public:
    void foo() //Here we have some method called foo.
    {
        std::cout << "Base::foo()\n";
    }
};

class Derived : public Base
{
public:
    void foo() //Here we override the Base::foo() with Derived::foo()
    {
        std::cout << "Derived::foo()\n";
    }
};

int main()
{
    Base *base1 = new Base;
    Derived *der1 = new Derived;
    base1->foo(); //Prints "Base::foo()"
    der1->foo();  //Prints "Derived::foo()"
}

If I have the above stated classes, I can call the foo method from any of Base or Derived classes instances, depending on what ::foo() I need. But there is some kind of problem: what if I need the Derived class instance, but I do need to call the Base::foo() method from this instance?

The solve of this problem may be next: I paste the next method to the class Derived

public:
void fooBase()
{
    Base::foo();
}

and call Derived::fooBase() when I need Base::foo() method from Derived class instance.

The question is can I do this using using directive with something like this:

using Base::foo=fooBase; //I know this would not compile.

?


Solution

  • der1->Base::foo();  //Prints "Base::foo()"
    

    You can call base class method using scope resolution to specify the function version and resolve the ambiguity which is useful when you don't want to use the default resolution.

    Similar (Not exactly same case) example is mentioned @ cppreference

    struct B { virtual void foo(); };
    struct D : B { void foo() override; };
    int main()
    {
        D x;
        B& b = x;
        b.foo(); // calls D::foo (virtual dispatch)
        b.B::foo(); // calls B::foo (static dispatch)
    }