0

Consider the following snippet of code

#include <iostream>

using namespace std;

class Base
{
public:
    virtual void Foo(int a) {cout << "Base::Foo(n)" << endl;}
    virtual void Foo(int a, int b){cout << "Base::Foo(n,n)" << endl;}
    
};

class Derived : public Base
{
public:
    
    void Foo(int a, int b) {cout << "Derived::Foo(n,n)" << endl;}
      
};


int main()
{   int n;
    {
        Base* b=new Derived();
    
    b->Foo(n); //uses Base:Foo(n)
    b->Foo(n,n); // uses Derived:Foo(n,n)
    delete b;
    }
    {
    Derived d;
    d.Foo(n,n); //uses Derived:Foo(n,n)
    d.Base::Foo(n); // uses Base::Foo(n)
    d.Foo(n); // causes compiler error
    }          
    return 0;
}

It would seem consistent with the rules of overloading that the derived class definition of Foo(int,int) should overload Base::Foo(int,int), but not hide Base::Foo(int). Indeed, in the first block of main, b->Foo(int,int) runs Derived::Foo(int,int). Yet, in the second block, we cannot call Base::Foo(int) unless with specify explicitely. This seems counterintuitive. What is the rationale for that?

user3646557
  • 305
  • 2
  • 8

0 Answers0