C++ inheritance and function overloading

· Read in about 2 min · (407 words) ·

Here is a simple looking C++ program, which has two classes A and B ( which derives from A ). A has a function fun() which B tries to overload as fun(int). Sounds simple and the program looks correct but it doesn’t compile. Have a look at http://codepad.org/NQ3JNuRr .

Its hard to digest for it is an obvious code to compile in C++. The code listing is as below:

#include<iostream>
using namespace std;

class A{
public:
  void fun(){cout<<"fun\n";}
};

class B: public A{
  void fun(int i){cout<<"funB\n";}
};

int main()
{
  B b;
  b.fun();
}

This typical case has two work-arounds:

It looked like to puzzle to me, but its clearly mentioned in section “13.2 - Declaration matching” from the C++ International Standard ( which can be found here http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf ) and I quote:

Two function declarations of the same name refer to the same function if they are in the same scope and have equivalent parameter declarations (13.1). A function member of a derived class is not in the same scope as a function member of the same name in a base class.

Example:

     class B {
     public :
          int f ( int );
     };
     class D : public B {
     public :
          int f ( char *);
     };

Here D::f(char*) hides B::f(int) rather than overloading it.

     void h ( D * pd )
    {
          pd - > f (1);            // error:
                                   // D::f(char*) hides B::f(int)
          pd - > B :: f (1);       // OK
          pd - > f ( " Ben " );    // OK, calls D::f
    }

Its all a problem with getting the scope of functions correct. So when we chose using A::fun inside class B, we bring the function A::fun in same scope as of B::fun(int). When we call the function as b.A::fun(), we clearly specify to the compiler that we want to use fun() from class A’s scope. That way the compiler will know how to resolve the function names. This is simply because the standard says so. I wonder whether there is sufficient RTTI data which can be used to avoid specifying scope when coding for such a case, so that the function resoultion could be deferred til the runtime. At the run-time the function signature resolution could be done upwards in the class hierarchy. What could be the performance implication in doing so?