+ 1

Virtual functions

Hello. Today I want to ask you about virtual functions in C++. I can’t understand one thing. If in BASE class A we declarated method f(){cout<<“inside A”;} and then, in CHILD class B, we declarated the same method but now f(){cout<<“inside B”;}. After this we create an object of CHILD class and call f(), so, after compilation , the output will be “inside B. But why? We didn’t use virtual void f() in the BASE class. Also with virtual, result will be the same. But why don’t child class output “inside A”? Tell me please why do the compiler work so?

13th Sep 2018, 6:59 PM
Fiodar Otsuma
Fiodar Otsuma - avatar
2 RĂ©ponses
+ 2
Fiodar Otsuma good question.. let me try to clear your doubt. class B is inherited from A and b has also method f()..so, A has it's own f() and B has it's own f (). whatever object (not pointer) you use, it's method will be called... A a;a.f(); // method of class A B b;b.f();//method of class B this was for objects..now refer below for pointer: A* pa = new A; pa->f(); // method from A as pointer is of class A nd points to class A object B* pa = new B; pb->f(); // method from B as pointer is of class B nd points to class B object A* pab = new B; pab->f(); // as pointer is of class A nd points to class B object.. without virtual, A method and with virtual B method will be called feel free to ask for query..
14th Sep 2018, 1:06 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
The class B has both version of f(), A::f() and B::f(). Methods of A class will call A::f() because they know nothing about B. Adding virtual feature allows to call methods, defined in B class inside A. Just add bar() function to A that calling foo() and check how virtual keyword changes behavior. The same situation with pointers and references. You can put address of B instance into A* pa or A& ra because it could downcast. Then you can call f() through it pa->foo() and check the difference.
13th Sep 2018, 7:12 PM
Sergey Ushakov
Sergey Ushakov - avatar