0

Why this program gives error. It doesn't gives error if we remove the definition of fun() function in derived class B. Why it be

#include<iostream> using namespace std; class A { public: void fun(){cout<<"Hi\n";} void fun(int x) { cout<<x; } }; class B:public A { public: void fun() { cout<<"Hello\n"; } }; int main() { B ob; ob.fun(); ob.fun(2); A x; x.fun(); return 0; }

13th Jun 2021, 6:00 AM
Rahul Kumar
Rahul Kumar - avatar
2 Réponses
+ 1
I think you probably want to also override the fun( int ) member function. Currently your B class has only an override for fun() member function, thus compiler cannot find a matching function fun( int ) and raised the error. Or don't override anything in class B, so calls to fun() and fun( int ) will instead refer to the ones defined in class A. Not sure what you want here ...
13th Jun 2021, 6:14 AM
Ipang
+ 1
This is how C++ name lookup works, it looks in the current scope for matching name, and continue looking in outer enclosing scopes only if there isn't any match. In your case, there is already a function named "fun" in the derived class, so the compiler will not go searching for it in base class, thus "hiding" all the potential overloads of the function in base class. One possible fix is to use the "using" keyword to "un-hide" the base class overloads like this 👇 https://code.sololearn.com/cMe6XxUgNfHK/?ref=app Other (as mentioned by Ipang ) is to override every overload of the function ( "fun" in your case ) in your derived class
13th Jun 2021, 7:58 AM
Arsenic
Arsenic - avatar