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; }

5th Jul 2017, 3:02 PM
Kushagra Agarwal
Kushagra Agarwal - avatar
7 Answers
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
5th Jul 2017, 4:15 PM
Jojo
+ 1
Ook.. thank you very much
5th Jul 2017, 4:39 PM
Kushagra Agarwal
Kushagra Agarwal - avatar
+ 1
I thank you, thanks to you I know I have to work on Inheritance and Ploymorphism...
5th Jul 2017, 4:41 PM
Jojo
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
5th Jul 2017, 3:14 PM
Jojo
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..*/
5th Jul 2017, 3:22 PM
Kushagra Agarwal
Kushagra Agarwal - avatar
0
Then answer should be 2 only as b is the base class for c. Why 3?
5th Jul 2017, 4:26 PM
Kushagra Agarwal
Kushagra Agarwal - avatar
0
It's because of the virtual function of a. b inherits of a's virtual function... so b's f() become virtual
5th Jul 2017, 4:37 PM
Jojo