c++ - Overloading a base class function in the derived class -
c++ - Overloading a base class function in the derived class -
why if base of operations class function overloaded in derived class, base of operations class version of function (even if public) not accessible through object of derived class?
eg:
#include <iostream> #include <string> using namespace std; class base of operations { public: void f(int i) { cout << "\ninteger: " << << endl; } }; class derived : public base of operations { public: void f(string s) { cout << "\nstring: " << s << endl; } }; int main() { base of operations b; derived d; //d.f(5); doesn't work d.f("hello"); //d.base::f(5); works though homecoming 0; }
name lookup performed before overload resolution. name lookup starts in 1 scope, if doesn't find declaration of name, searches enclosing scope, , on until finds name. in case d.f
finds declaration void derived::f(string)
. if there no declaration of fellow member f
in derived
name lookup proceed search base of operations class. after name has been found compiler determine whether there appropriate overload, , if so, overload best match.
note can redeclare base of operations class function in derived class, forcefulness found:
class derived : public base of operations { public: using base::f; void f(string s) { cout << "\nstring: " << s << endl; } };
now name lookup find both overloads of f
, overload resolution determine 1 call.
c++
Comments
Post a Comment