Search code examples
c++optimization

Is it always true that virtual function cannot be inlined in C++?


It is said that virtual functions cannot be inlined. Is it always true that if a function is declared virtual, it cannot be inlined anywhere in the code, or is it applicable only under certain situations? (eg., calling method from a base pointer vs. calling method on a reference, etc.)


Solution

  • No, virtual functions can indeed be inlined. Virtual dispatch is only used when calling a virtual method polymorphically (i.e., on a pointer or reference to an object). However, when a virtual method is called on an object value, virtual dispatch is not used and the compiler is free to inline as it sees fit.