Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Can Virtual Functions be Inlined in C++?

  • Difficulty Level : Medium
  • Last Updated : 01 Dec, 2021

Virtual functions are member functions that are declared in the base class using the keyword virtual and can be overridden by the derived class. They are used to achieve Runtime polymorphism or say late binding or dynamic binding. 

Inline functions are used to replace the function calling location with the definition of the inline function at compile time. They are used for efficiency. The whole idea behind the inline functions is that whenever an inline function is called code of the inline function gets inserted or substituted at the point of the inline function call at compile time. Inline functions are very useful when small functions are frequently used and called in a program many times. 

Take a step-up from those "Hello World" programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.

By default, all the functions defined inside the class are implicitly or automatically considered as inline except virtual functions. 

Note: inline is a request to the compiler and its compilers choice to do inlining or not.

Can virtual functions be inlined?

Whenever a virtual function is called using a base class reference or pointer it cannot be inlined because the call is resolved at runtime, but whenever called using the object (without reference or pointer) of that class, can be inlined because the compiler knows the exact class of the object at compile time.


// CPP program to demonstrate that
// virtual functions can be inlined
#include <iostream>
using namespace std;
class Base {
    virtual void who() { cout << "I am Base\n"; }
class Derived : public Base {
    void who() { cout << "I am Derived\n"; }
int main()
    // Part 1
    Base b;
    // Part 2
    Base* ptr = new Derived();
    return 0;
I am Base
I am Derived

Explanation: In Part 1, the virtual function who() is called through the object of the class. Since it will be resolved at compile-time, so it can be inlined. In Part 2, the virtual function is called through a pointer, so it cannot be inlined.

This article is contributed by Meet Pravasi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!