Search code examples
c++inheritanceoverloadingoverridingoverload-resolution

Simultaneous overriding and overloading in C++


Hello everyone I am puzzled about the following piece of C++ code in which overloading and overriding are somehow simulataneous.

Here are the errors that my compiler gives (mingw32-g++ inside Code::Blocks 13.12)

error: no matching function for call to 'Derived::show()'
note:  candidate is:
note:  void Derived::show(int)
note:  candidate expects 1 argument, 0 provided

Here is the code that produces them.

    #include <iostream>
    using namespace std;

    class Base{
    public:
      void show(int x){
        cout<<"Method show in base class."<<endl;
      }
      void show(){
        cout<<"Overloaded method show in base class."<<endl;
      }
    };

    class Derived:public Base{
    public:
      void show(int x){
        cout<<"Method show in derived class."<<endl;
      }
    };

    int main(){
      Derived d;
      d.show();
    }

I tried to declare Base::show() as virtual. Then I tried the same with Base::show(int). Doesn't work either.


Solution

  • This is name hiding. Derived::show hides the methods with the same name in Base. You can introduce them by using.

    class Derived:public Base{
    public:
      using Base::show;
      void show(int x){
        cout<<"Method show in derived class."<<endl;
      }
    };