How vptr and vtable works | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How vptr and vtable works

Assume that class B is base class and D is derived class. Both has virtual function test(). Now , in main function; I have B* pB = new D; 1. Does this means after compilation , both class has vtable ? B class vtable points to function test from B and D class vtable points to function test from D. 2. As pb is pointing to D, pb will point to vptr of D. But when this happens and how ? We just created two different vtable at compile time.. when run time linking happens and how ? Different articles speaks that constructor implements additional responsibilities of binding vtable to vptr for each object. Is this understanding correct... If so, how ? Here , we are not creating any object due to pointer and new still how linking happens from constructor ?

17th Mar 2021, 5:08 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Answers
+ 2
Thanks Anthony Maina I got your points .. but one more query... Derived will also call constructor and hence derived object will have both vptr... So again it's two vptr for derived class objects
23rd Mar 2021, 1:19 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
For the first question,the answer is yes. The compiler will set up two vtables one for class B and the other for class D.(Also keep in mind that there is usually only one vtable for each class) And also yes, the vtable for class B will only contain one entry, which is a pointer to B's function test. The same logic applies to class D and its vtable.
21st Mar 2021, 10:57 PM
Anthony Maina
Anthony Maina - avatar
+ 1
For the second question, yes your understanding is correct, at least as far as I know, that the constructor points the vptr of each object to the vtable of that object's class.How, you ask? Well,the vtable is just a static array of pointers to virtual functions.So all what the constructor does, is point the vptr to this array during object instantiation. Contrary to your belief, the new keyword actually does create a new object. so in this statement B* pB = new D; , we only have one object, which is the dynamically allocated object of type D. pB is just a variable pointing to that object. So in this case we only have one vptr, which is the one stored in the D object. So an attempt to access the member function test() using pB will result in D's test being called, since the lookup for that test function will be done in D's vtable and not B's as one might assume.
21st Mar 2021, 11:06 PM
Anthony Maina
Anthony Maina - avatar
0
Yeah, I would say so.
23rd Mar 2021, 1:29 PM
Anthony Maina
Anthony Maina - avatar