Inlining Virtual Member Functions

Inlining Virtual Member Functions

Generally, compilers can’t inline a virtual function call if the it’s resolved dynamically. Therefore, declaring a virtual member function inline might seem pointless. However, not every call of a virtual function is resolved dynamically; in some cases, the compiler can resolve the call statically, as if the function weren’t virtual. In situations like these, the compiler can also inline the call. For example:

   class Base  {  public:    inline virtual int f() { return 0; }  };  int main()  {    Base b;    b.f(); // resolved statically; call can be inlined  }

The invocation of f() is resolved statically because b is not a pointer or a reference. The compiler can also expand the call inline, thereby optimizing the code even further.


Share the Post: