Open In App

Can Virtual Functions be Inlined in C++?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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. 

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.
 

C++




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


Output

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.


Last Updated : 01 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads