Related Articles

Related Articles

Hiding of all overloaded methods with same name in base class
  • Difficulty Level : Medium
  • Last Updated : 04 Nov, 2020

In C++, if a derived class redefines base class member method then all the base class methods with same name become hidden in derived class. 
For example, the following program doesn’t compile. In the following program, Derived redefines Base’s method fun() and this makes fun(int i) hidden.

CPP

filter_none

edit
close

play_arrow

link
brightness_4
code

#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";
    }
};
 
// Driver Code
int main()
{
    Derived d;
    d.fun(5); // Compiler Error
    return 0;
}

chevron_right


Even if the signature of the derived class method is different, all the overloaded methods in base class become hidden. For example, in the following program, Derived::fun(char ) makes both Base::fun() and Base::fun(int ) hidden.

CPP

filter_none

edit
close

play_arrow

link
brightness_4
code

#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:
    // Makes Base::fun() and Base::fun(int )
    // hidden
    int fun(char c)
    {
        cout << "Derived::fun(char c) called";
    }
};
 
// Driver Code
int main()
{
    Derived d;
    d.fun('e'); // Compiler Error
    return 0;
}

chevron_right


Output

Derived::fun(char c) called

Note that the above facts are true for both static and nonstatic methods.

There is a way mitigate this kind of issue. If we want to overload a function of a base class, it is possible to unhide it by using the ‘using’ keyword.



C++

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
 
using namespace std;
 
class Base
{
public:
    int fun()
    {
        cout<<"Base::fun() called";
    }
};
 
class Derived: public Base
{
public:
    using Base::fun;
     
    int fun(char c)  // Makes Base::fun() and Base::fun(int ) hidden
    {
        cout<<"Derived::fun(char c) called";
    }
};
 
int main()
{
    Derived d;
    d.fun();  // Works fine now 🙂
    return 0;
}

chevron_right


Output

Base::fun() called

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :