What is wrong with the following code? He does not compile

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

When commenting on obj.Display(10) it works.

+7
source share
3 answers

You need to place -

 using Base::Display ; // in Derived class 

If the method name matches the Derived class, the compiler will not look for the Base class. Therefore, to avoid this behavior, put using Base::Display; . The compiler will then study the Base class if there is any method that can actually accept an int as an argument to Display .

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

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

Why?

Read this explanation from AndreyT

You can enter these hidden names using the using declaration:

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

In addition, void main() is non-standard. Use int main()

+3
source

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

+2
source

All Articles