1

Why won't the compiler call the base class function (parameterized one) through the derived class object? The derived class inherits the function from the base class, right?

#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);
    return 0;
}

However, when I used the scope resolution operator, I got the desired output. Can anyone provide me a logical explanation behind this? Can I still call the base class function (parameterized one) through derived class object? Thanks!

int main() 
{
    Derived d;
    d.Base::fun(5);
    return 0;
}
Moiz Sajid
  • 644
  • 1
  • 10
  • 20

1 Answers1

4

The derived function Derived::fun() hides all members with the same name from the base class. So you can only use the base class member via scope resolution. To avoid hiding, you can do:

class Derived: public Base
{
public:
    int fun() {  cout << "Derived::fun() called"; }
    using Base::fun;
};
aschepler
  • 70,891
  • 9
  • 107
  • 161