Jul 16, 2019 in C++


What are VTABLE and VPTR?

1 Answer

Jul 16, 2019

vtable is a table of function pointers. It is maintained per class.
vptr is a pointer to vtable. It is maintained per object (See this for an example).
Compiler adds additional code at two places to maintain and use vtable and vptr.
1) Code in every constructor. This code sets vptr of the object being created. This code sets vptr to point to vtable of the class.
2) Code with polymorphic function call (e.g. bp->show() in above code). Wherever a polymorphic call is made, compiler inserts code to first look for vptr using base class pointer or reference (In the above example, since pointed or referred object is of derived type, vptr of derived class is accessed). Once vptr is fetched, vtable of derived class can be accessed. Using vtable, address of derived derived class function show() is accessed and called.

Click here to read more about C++
Click here to read more about Insurance

Related questions

Jul 16, 2019 in C++
Jul 16, 2019 in C++
Jul 16, 2019 in C++