Virtual function | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Virtual function

now the output is cc When i take virtual from the class A the output is bc. why does it happen ? https://code.sololearn.com/cy4RgGt7HDRt/?ref=app

3rd Aug 2018, 3:49 PM
Fidan Rli
Fidan Rli - avatar
10 Answers
+ 3
Ketan Lalcheta thanks a lot . i am learning it newly. thanks in advance .
3rd Aug 2018, 5:20 PM
Fidan Rli
Fidan Rli - avatar
+ 2
Borislav Kalinski when i use virtual pointer refers to derived class ? i got it thanks .
3rd Aug 2018, 4:32 PM
Fidan Rli
Fidan Rli - avatar
+ 2
Borislav Kalinski no. i can understand everything. thanks anyway
3rd Aug 2018, 4:38 PM
Fidan Rli
Fidan Rli - avatar
+ 1
Borislav Kalinski writing f as method in class A . without virtual .
3rd Aug 2018, 4:19 PM
Fidan Rli
Fidan Rli - avatar
+ 1
yeap i knew it . i meant why was the output different when i use it . Borislav Kalinski
3rd Aug 2018, 4:23 PM
Fidan Rli
Fidan Rli - avatar
+ 1
Because of pointer when you use it you call f from base class not f from divired class.
3rd Aug 2018, 4:28 PM
B K
+ 1
Sorry for my bad explanation if i rearly helped no problem.
3rd Aug 2018, 4:35 PM
B K
0
What do you mean by taking virtual from class A?
3rd Aug 2018, 4:17 PM
B K
0
Virtual is used if you want to modify the method in devired class.
3rd Aug 2018, 4:21 PM
B K
0
Fidan Rli B* P = & c; This means you have a pointer of Class B which is pointing to object of Class C... B class method is called by p->f() as p is nothing but pointer of Class B.... this is the normal scenario... if we put virtual keyword, compiler checks in details (using vpointer and vtable) and decides to go with class c method as p is pointing to class c object... I would suggest you to refer any article on polymorphism to understand this in detail... feel free to ask if anything you could not understand from any article you gonna read on this... Happy learning ☺️😊
3rd Aug 2018, 5:05 PM
Ketan Lalcheta
Ketan Lalcheta - avatar