How Virtual Tables Work in the Itanium C++ ABI

https://lobste.rs/rss Hits: 26
Summary

Virtual functions are one of C++’s core features, enabling runtime polymorphism. Most C++ programmers use them regularly, yet few understand how they work in practice. What does the compiler actually generate when you declare a function virtual? How does the program figure out which implementation to call at runtime? Where is the vtable data actually stored? This blog post is focused on answering these questions.The C++ standard specifies behavior but not implementation. This post describes the Itanium C++ ABI used by most platforms, with the notable exception of Microsoft MSVC.A Basic Example#Consider these classes with virtual functions:struct Base { virtual void foo() { __builtin_printf("Base::foo\n"); } virtual void bar() { __builtin_printf("Base::bar\n"); } virtual ~Base() {} }; struct Derived : Base { void foo() override { __builtin_printf("Derived::foo\n"); } }; void call_foo(Base* b) { b->foo(); // Which foo() gets called? } int main() { Base base; Derived derived; call_foo(&base); // Should call Base::foo call_foo(&derived); // Should call Derived::foo } The compiler doesn’t know at compile time what type b points to in call_foo(). The function needs to dispatch to the correct foo() implementation based on the actual runtime type of the object. This is what vtables (short for virtual tables) enable.The Virtual Table Structure#Let’s see what a vtable actually looks like. GCC has a useful flag -fdump-lang-class that dumps the class and vtable layout:g++ -fdump-lang-class example.cpp GCC should emit a file named a-example.cpp.001l.class containing info about the classes and vtables dumps.Clang can dump similar information too, although the interface is different:clang++ -Xclang -fdump-record-layouts -Xclang -fdump-vtable-layouts example.cpp I learned about this from Dumping a C++ object’s memory layout with Clang.I think GCC has a slightly nicer output format, so all quoted output below is from gcc -fdump-lang-class.For our Base class, GCC outputs:Vtable for B...

First seen: 2026-05-26 12:33

Last seen: 2026-05-27 13:52