Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Out-of-Line Virtual Method

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.

like image 425
Daniel Eggert Avatar asked May 28 '13 20:05

Daniel Eggert


People also ask

What is the meaning of virtual method?

What Does Virtual Method Mean? A virtual method is a declared class method that allows overriding by a method with the same derived class signature. Virtual methods are tools used to implement the polymorphism feature of an object-oriented language, such as C#.

Why is virtual method called virtual?

'virtual function' means a member function where the specific implementation will depend on the type of the object it is called upon, at run-time. The compiler and run-time support of the language contrive to make this happen. The keyword 'virtual' in C++ was taken from Simula, which had impressed Bjarne Stroustrup.

What is the purpose of virtual methods?

Basically, a virtual function is used in the base class in order to ensure that the function is overridden. This especially applies to cases where a pointer of base class points to an object of a derived class.

Can virtual method have body?

Pure virtual functions (when we set = 0 ) can also have a function body.


1 Answers

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.

like image 171
Dark Falcon Avatar answered Oct 16 '22 18:10

Dark Falcon