Out-of-Line Virtual Method

Daniel Eggert picture Daniel Eggert · May 28, 2013 · Viewed 10.6k times · Source

What exactly is a out-of-line virtual method and why does it affect link times?

LLVM Coding Standards says

If a class is defined in a header file and has a vtable (either it has virtual methods or it derives from classes with virtual methods), it must always have at least one out-of-line virtual method in the class. Without this, the compiler will copy the vtable and RTTI into every .o file that #includes the header, bloating .o file sizes and increasing link times.

Answer

Dark Falcon picture Dark Falcon · May 28, 2013

The compiler must emit a vtable for classes with virtual methods. This contains the pointers to these methods. If all the virtual methods are inline (defined in the header), then the compiler doesn't know which translation unit (.cpp file) to emit the vtable within, so it emits a copy in all of them and the linker gets to deal with it. This makes extra work and bloat in the object files. If, on the other hand, a virtual function is defined out-of-line (in a .cpp), the vtable can be emitted there and thus only one copy will be emitted. The same applies to the RTTI.