+ 6

[C++] Why the class B can't inherit f(int x) of class A? please help me.

Could someone explain why the class B can't inherit f(int x) of class A? I still dont get it. How to modify class B , let it inherit f(int x ) of class A? #include <iostream> using namespace std; class A { public: int f() {cout<<3;} int f(int x) {cout<<x;} }; class B: public A { public: int f() {cout<<5;} }; int main() { B ob; ob.f(7); }

8th May 2017, 12:48 AM
Ibizaj
Ibizaj - avatar
4 odpowiedzi
+ 10
either you should remove all the functions in side class B or to redefine them all in side class B #include <iostream> using namespace std; class A { public: int f() {cout<<3;} int f(int x) {cout<<x;} }; class B: public A { }; int main() { B ob; ob.f(7); } or #include <iostream> using namespace std; class A { public: int f() {cout<<3;} int f(int x) {cout<<x;} }; class B: public A { public: int f() {cout<<5;} int f(int x) {cout << x;} }; int main() { B ob; ob.f(7); }
8th May 2017, 2:27 AM
Mohammad Dakdouk
Mohammad Dakdouk - avatar
+ 9
becuause class B must redefine the overloaded function in sides its declaration and this is not done in your code.
7th May 2017, 4:30 PM
Mohammad Dakdouk
Mohammad Dakdouk - avatar
+ 1
@Mohammad And how to modify class B to inherit f(int x) of class A? @kimanzi I saw output = 7, I confused.
8th May 2017, 12:54 AM
Ibizaj
Ibizaj - avatar
0
@Johnny why do you say B can't inherit f(int x) base method? Because you see at output of 7?
7th May 2017, 5:46 PM
kimanzi
kimanzi - avatar