Ganesh Kundapur
Ganesh Kundapur

Reputation: 545

Whats wrong with the following code? It's not compiling

#include <iostream> 
#include <vector>
using namespace std;

class Base
{
public:
      void Display( void )
      {
            cout<<"Base display"<<endl;
      }

      int Display( int a )
      {
            cout<<"Base int display"<<endl;
            return 0;
      }

};

class Derived : public Base
{
public:

      void Display( void )
      {
            cout<<"Derived display"<<endl;
      }
};


void main()
{
   Derived obj;
   obj.Display();  
   obj.Display( 10 );
}

$test1.cpp: In function ‘int main()’:  
test1.cpp:35: error: no matching function for call to ‘Derived::Display(int)’  
test1.cpp:24: note: candidates are: void Derived::Display()

On commenting out obj.Display(10), it works.

Upvotes: 7

Views: 214

Answers (3)

Prasoon Saurav
Prasoon Saurav

Reputation: 92942

You need to use the using declaration. A member function named f in a class X hides all other members named f in the base classes of X.

Why?

Read this explanation by AndreyT

You can bring in those hidden names by using a using declaration:

using Base::Display is what you need to include in the derived class.

Furthermore void main() is non-standard. Use int main()

Upvotes: 3

jonsca
jonsca

Reputation: 10381

You are masking the original function definition by creating a function in the derived class with the same name: http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.8

Upvotes: 2

Mahesh
Mahesh

Reputation: 34665

You need to place -

using Base::Display ; // in Derived class

If a method name is matched in the Derived class, compiler will not look in to the Base class. So, to avoid this behavior, place using Base::Display;. Then the compiler will look into the Base class if there is any method that can actually take int as argument for Display.

class Derived : public Base
{
    public:
    using Base::Display ;
    void Display( void )
    {
        cout<<"Derived display"<<endl;
    }
};

Upvotes: 2

Related Questions