Search code examples
c++polymorphismvirtualinline

Inheritance and inline?


I have been doing a lot of reading recently and whilst covering inheritance (and virtual functions) I keep stumbling across the "inline" keyword. Now I know what inline is in the normal sense- compiler may replace function calls with the exact code. However, the number of times I have seen it mentioned with regards to inheritance- is there some special reason for using inline within inheritance? I don't understand why it keeps being mentioned....

What extra role does an inline function have within inheritance/derived classes/virtual functions?


Solution

  • Yes, using inline on virtual functions is a waste of time. A virtual function has to be called through a virtual function table, which is made of function pointers. An inline function cannot be called by a pointer. It has to exist as a real function.

    There are some exceptions. Where the caller knows the exact object type it can skip the virtual function table entirely.

    Overuse of the virtual keyword can result in very slow code. Where the compiler might be able to inline and optimize three or four small function calls, with virtual functions it has to do actual function calls, making no assumptions about memory or register state between calls.