3

recently i came to know this - if a derived class redefines base class member method(s) then all the base class methods with same name become hidden in derived class.

#include<iostream>

using namespace std;

class Base
{
public:
int fun()
{
    cout<<"Base::fun() called";
}
int fun(int i)
{
    cout<<"Base::fun(int i) called";
}
};

class Derived: public Base
{
public:
int fun() 
{
    cout<<"Derived::fun() called";
}
};

int main()
{
Derived d;
d.fun(5);  // Compiler Error
return 0;
}

Error : In function 'int main()': Line 30: error: no matching function for call to 'Derived::fun(int)' compilation terminated due to -Wfatal-errors.

but just wanna know the reason behind it? why is it not calling fun(int i) method of Base Class since Derived class is derived from Base

Umal Stack
  • 241
  • 4
  • 7

2 Answers2

5

The fundamental reason is to make code more robust.

struct Base {
};

struct Derived : Base {
    void f(long);
    void g() { f(3); } // calls Derived::f
}

Now suppose Base is defined in a library, and you get an update to that library and the update changes the definition of Base:

struct Base {
    void f(int);
};

Now suppose that searches for overloaded functions didn't stop when a name was found. In that case, Derived::g would call Base::f instead of Derived::f, and your derived class would quietly do something completely different from what it did before, and different from what it was designed and documented to do.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
2

You've already discovered that derived-class overloads will shadow (prevent the visibility of) base-class methods by the same name but different parameters. Let's just claim this was done for some historical or perceived safety reason, and look at a fix:

class Derived: public Base
{
public:
  using Base::fun; // expose the base-class method
  int fun() 
  {
    cout<<"Derived::fun() called";
  }
};
John Zwinck
  • 239,568
  • 38
  • 324
  • 436