7
#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.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
Ganesh Kundapur
  • 525
  • 1
  • 6
  • 13
  • What compiler are you using ? It looks like `gcc` but is this the most recent code ? Why you get `$test1.cpp: In function ‘int main()’:` even though you have defined main as `void main()` ? –  Mar 17 '11 at 08:09
  • tried with gcc and vc++. Copied code from the vc++ editor, pasted gcc output. – Ganesh Kundapur Mar 17 '11 at 08:14

3 Answers3

3

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()

Community
  • 1
  • 1
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
  • 2
    He has defined main as `void main()` but how come he gets `$test1.cpp: In function ‘int main()’:` ? –  Mar 17 '11 at 08:07
  • 5
    @Muggen: It's illegal to declare `main` as having a return type of anything other than `int`. This particular implementation seems to just ignore this error and treat the code as if it declared `main` correctly. – CB Bailey Mar 17 '11 at 08:11
2

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;
    }
};
Mahesh
  • 34,573
  • 20
  • 89
  • 115
2

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

jonsca
  • 10,218
  • 26
  • 54
  • 62