The virtual table is a lookup table of functions used to resolve function calls in a dynamic/late binding manner.
every class that uses virtual functions (or is derived from a class that uses virtual functions) is given it’s own virtual table.
This table is simply a static array that the compiler sets up at compile time.
A virtual table contains one entry for each virtual function that can be called by objects of the class.
Each entry in this table is simply a function pointer that points to the most-derived function accessible by that class.
(most-derived function指的是 , 因為derived class也可以呼叫base class的function ,
但其可以控制的最大權利還是在於自己的function , 在這裡指的意思就是說 ,
derived class的object 會呼叫其本身的virtual function.)
the compiler also adds a hidden pointer to the base class, which we will call *__vptr.
*__vptr is set (automatically) when a class instance is created so that it points to the virtual table for that class.
Unlike the *this pointer, which is actually a function parameter used by the compiler to resolve self-references, *__vptr is a real pointer.
Consequently, it makes each class object allocated bigger by the size of one pointer.
It also means that *__vptr is inherited by derived classes, which is important.
for example :
class
Base
{
public
:
virtual
void
function1() {};
virtual
void
function2() {};
};
class
D1:
public
Base
{
public
:
virtual
void
function1() {};
};
class
D2:
public
Base
{
public
:
virtual
void
function2() {};
};
Because there are 3 classes here, the compiler will set up 3 virtual tables: one for Base, one for D1, and one for D2.
ref : http://www.learncpp.com/cpp-tutorial/125-the-virtual-table/