c++functionusing-declarationname-hiding

Function hiding in c++


I was trying out few concepts of function hiding in c++. So here in the derived class I've used scope resolution operator using base::fun to provide scope of base class in derived class. My objective is to print cout<<" base "<< x; but the output only prints derived class cout. Any reasons why and how to solve? i.e it should print both base and derived class value. I'm new to c++, so sorry for any mistakes.The code is shown below:

#include <stdio.h>
#include <iostream>
using namespace std;

class base
{
public:
int fun(int x)
{
    cout<<" base "<< x;
    return x;
}
};
class derived:public base
{
public:
using base::fun;
void fun(int a)
{
    cout<<" derived "<< a;
}
};

int main()
{
    derived d;
    d.fun(10);
    return 0;
}

Solution

  • it should print both base and derived class value

    No. Only one function would be selected and called. Then the problem is that which one should be selected. In this case derived::fun is selected; because for using declaration,

    If the derived class already has a member with the same name, parameter list, and qualifications, the derived class member hides or overrides (doesn't conflict with) the member that is introduced from the base class.

    You might call the base one by specifying explicitly:

    d.base::fun(10);
    

    LIVE