0
why output is not 2?
#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(); return 0; }
7 Respuestas
0
You know what ? You've asked a very good question...
I've told you something wrong :
p->f(); isn't like c.f();
When you create a new c from a b pointer, if two methods are in both class, the one of the base class is called unless it's a virtual function.
Quite difficult... ask if you still have questions
+ 1
Ook.. thank you very much
+ 1
I thank you, thanks to you I know I have to work on Inheritance and Ploymorphism...
0
c inherits from b.
b *p=new c; // pointer on an object c.
p is the pointer. *p is the 'value' of the object pointed (c) so *p->f(); is like c.f();
Ask if you don't understand
0
Let us ignore the virtual keyword. Now consider -
int main() {
a *p = new b;
p->f(); /*equivalent to b.f()
but output is 1... so according to this o/p of code given in ques should be 2..*/
0
Then answer should be 2 only as b is the base class for c. Why 3?
0
It's because of the virtual function of a.
b inherits of a's virtual function...
so b's f() become virtual