Virtual functions

My question is with a link to this question , which explains how virtual functions work in the case of slicing objects that ultimately call the virtual function of the base class and Wikipedia article , which explains the structure of the virtual table for the derived class for the code below

class A{ public: virtual void func(){ cout<<"\n In A:func";} }; class B:public A{ public: virtual void func(){ cout<<"\n In B:func";} }; main(){ A *ptr1 = new B(); A oA = *ptr1; oA.func(); } DerviedClassObjectB: +0: pointer to virtual method table of B virtual method table of B: +0: B::func 

Above the exits of the program "In A :: func".

But as without a virtual table for class B, knowledge of the base class A :: func ends with a call to A :: func

+5
source share
2 answers

"Virtual table for class B "? The virtual table for class B does not participate in the oA.func() call at oA.func() . The oA object is of type A , which means that its virtual table is class A

In addition, most compilers optimize the oA.func() call so that it does not use any virtual tables at all. Since the oA type oA known at compile time, the call to oA.func() can be immediately routed to A::func without using any virtual tables.

+13
source
 A oA = *ptr1; 

This copies any member variables to the new object A. The vtable pointer is not a normal member variable and is not copied. Thus, any subsequent virtual functions called against this object will act as if it were object A, because it is object A.

+12
source

All Articles