tags:

views:

80

answers:

3
class A
{
     public:
          int func1()
          {
                cout<<"A's func1";
          }
}

class B:public A
{
     public:
          int func1()
          {
                cout<<"B's func1";
          }
}

in the above code snippet , is the function ' func1()' getting overloaded in class B ?

or getting overrided by class B ..?

+11  A: 

Overriding can only happen when the base class member function is declared virtual. Overloading can only happen when the two functions have different signatures.

Neither of these conditions applies here. In this case, B::func1 is simply hiding A::func1.

Side note: the condition I indicated for overloading is necessary but not sufficient in this case. Even if you declared B::func1(int i), so that the signatures were different, B::func1 would still hide A::func1 because of C++'s name lookup rules.

The gory details: When you write b->func1(), C++ looks for the name func1 first in the scope of B; since B has that name in its scope, the compiler ends its search right there and then, and will not look any further, even though b->func1() ultimately fails to match the signature B::func1(int i). You can change this behaviour, and overload A::func1() and B::func1(int i) by adding using A::func1 to the definition of B, thus:

class B: public A
{
public:
    using A::func1;
    int func1(int i)
    {
        cout << "B's func1(" << i << ")\n";
    }
};

Also, don't forget the required semicolons at the end of each class definition.

Marcelo Cantos
A: 

See the difference between overriding and overloading. But this one is actually hiding.

Draco Ater
+2  A: 

If you had made func1 in class A virtual then class B would be overriding func1, since it is not virtual, you are hiding the func1 implementation in A.

Chris Taylor