Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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

like image 274
Ganesh Kundapur Avatar asked Mar 17 '11 08:03

Ganesh Kundapur


3 Answers

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

like image 197
Prasoon Saurav Avatar answered Dec 08 '22 17:12

Prasoon Saurav


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;
    }
};
like image 35
Mahesh Avatar answered Dec 08 '22 16:12

Mahesh


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

like image 28
jonsca Avatar answered Dec 08 '22 15:12

jonsca