B-Mac
B-Mac

Reputation: 567

Overloading a base class function in the derived class

Why is it that if a base class function is overloaded in the derived class, the base class version of the function (even if public) is not accessible through an object of the derived class?

Eg:

#include <iostream>
#include <string>

using namespace std;

class Base {
public:
    void f(int i) {
        cout << "\nInteger: " << i << endl;
    }
};

class Derived : public Base {
public:
    void f(string s) {
        cout << "\nString: " << s << endl;
    }
};


int main() {
    Base b;
    Derived d;
    //d.f(5);  Doesn't work
    d.f("Hello");
    //d.Base::f(5); works though
    return 0;
}

Upvotes: 1

Views: 148

Answers (2)

R Sahu
R Sahu

Reputation: 206717

If you want to be able the Base::f in addition to Derived::f, you can add a line

using B::f;

in Derived.

class Derived : public Base {
   public:
      using Base::f;
      void f(string s) {
         cout << "\nString: " << s << endl;
      }
};

Now you can use:

Derived d;
d.f(10);
d.f("Hello");

Upvotes: 0

Brian Bi
Brian Bi

Reputation: 119552

Name lookup is performed before overload resolution. Name lookup starts in one scope, then if it doesn't find a declaration of the name, it searches an enclosing scope, and so on until it finds the name. In this case d.f finds the declaration void Derived::f(string). It is only if there were no declaration of a member f in Derived that name lookup would proceed to search the base class. Only after the name has been found does the compiler determine whether there is an appropriate overload, and if so, which overload is the best match.

Note that you can redeclare the base class function in the derived class, to force it to be found:

class Derived : public Base {
public:
    using Base::f;
    void f(string s) {
        cout << "\nString: " << s << endl;
    }
};

Now name lookup will find both overloads of f and then overload resolution will determine which one to call.

Upvotes: 1

Related Questions