Vtable in C++
Also known as virtual function table, dispatch table.
Introduction
A virtual table is a static array that contains entries for each virtual function. Each entry is a function pointer that points to the most-derived function.
For classes that have virtual functions, a hidden pointer will be added as a member of that class (*__vptr
)
Example
For the following example, a diagram indicating different vtables of each class can be shown below. Each *__vptr
points to a vtable belongs to a class.
Since foo1() is overriden by D1 and foo2() is overriden by D2, D1 vatble and D2 vtable will be updated during compile time, and foo1() in D1 now points to D1::foo1(), foo2() in D2 points to D2::foo2(). However, since D1 didn’t implement foo2(), foo2() in D1 vtable still points to Base::foo2(). Same for foo1() in D2.
1 | class Base |
1 | D1 foo1() |
References
Vtable in C++