why this output only comes 3 and why not output 123? #include<iostream> using namespace std; class A{ public: virtual void f(){cout<<1;} }; class B:public A{ public: void f(){cout<<2;} }; class C:public B{ public: void f(){cout<<3;} }; int main() { B *p=new C; p->f(); } | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

why this output only comes 3 and why not output 123? #include<iostream> using namespace std; class A{ public: virtual void f(){cout<<1;} }; class B:public A{ public: void f(){cout<<2;} }; class C:public B{ public: void f(){cout<<3;} }; int main() { B *p=new C; p->f(); }

24th Aug 2016, 2:21 PM
Lekhraj Singh
Lekhraj Singh - avatar
3 Answers
+ 2
This code output is 3. This is because p is a pointer of a C object, that has f() redefined in public. Does not return 123 because with the redefinition the code avoids the other f() versions. Anyway, this kind of question has been resolved few times with posibly more elaborated answers. You only have to search by tag.
24th Aug 2016, 3:51 PM
Néstor
Néstor - avatar
0
thanks Nestor
26th Aug 2016, 4:15 AM
Lekhraj Singh
Lekhraj Singh - avatar
0
Nestor, what tag name I use to search for this question?
26th Aug 2016, 4:16 AM
Lekhraj Singh
Lekhraj Singh - avatar