A vtable is a mapping that allows your C++ application properly reconcile the function pointers for the base classes that have virtual methods and the child classes that override those methods (or do not override them). A class that does not have virtual methods will not have a vtable.
A vtable is pointed to by a pointer (“vpointer”) at the top of each object, usually, where the vtable is the same for all objects of a particular class.
Though you can derive the pointer yourself, you can use gdb, ddd, etc.. to display it:
Source code:
class BaseClass { public: virtual int call_me1() { return 5; } virtual int call_me2() { return 10; } int call_me3() { return 15; } }; class ChildClass : public BaseClass { public: int call_me1() { return 20; } int call_me2() { return 25; } };
Compile this with:
g++ -fdump-class-hierarchy -o vtable_example vtable_example.cpp
This emits a “.class” file that has the following (I’ve skipped some irrelevant information at the top, about other types:
Vtable for BaseClass BaseClass::_ZTV9BaseClass: 4u entries 0 (int (*)(...))0 4 (int (*)(...))(& _ZTI9BaseClass) 8 (int (*)(...))BaseClass::call_me1 12 (int (*)(...))BaseClass::call_me2 Class BaseClass size=4 align=4 base size=4 base align=4 BaseClass (0x0xb6a09230) 0 nearly-empty vptr=((& BaseClass::_ZTV9BaseClass) + 8u) Vtable for ChildClass ChildClass::_ZTV10ChildClass: 4u entries 0 (int (*)(...))0 4 (int (*)(...))(& _ZTI10ChildClass) 8 (int (*)(...))ChildClass::call_me1 12 (int (*)(...))ChildClass::call_me2 Class ChildClass size=4 align=4 base size=4 base align=4 ChildClass (0x0xb76fdc30) 0 nearly-empty vptr=((& ChildClass::_ZTV10ChildClass) + 8u) BaseClass (0x0xb6a092a0) 0 nearly-empty primary-for ChildClass (0x0xb76fdc30)
Image may be NSFW.
Clik here to view.
Clik here to view.
