Overloading a Member Function Across Class Boundaries

Overloading a Member Function Across Class Boundaries

Since a class is a namespace, the scope for overloading a member function is confined to the class containing this function. Sometimes, it is necessary to overload the same function in its class as well as in a class derived from it. Using an identical name in a derived class merely hides the base class’ function, rather than overloading it:

 class B {public: void func(); };class D : public B { public:  void func(int n); //now hiding B::f, not overloading it  };D d;d.func();//compilation error. B::f is invisible in d; d.func(1); //OK, D::func takes an argument of type int

In order to overload (rather than hide) a function of a base class, you must inject it explicitly into the namespace of the derived class like this:

 class D : public B { using B::func; // inject the name of a base member function into the scope of Dpublic:  void func(int n); // D now has two overloaded versions of func()};D d;d.func ( ); // OKd.func ( 10 ); // OK


Share the Post: