Does the virtual functions be inlined?

As we know the functions that are available in the class are treated as inline functions. What about the virtual functions?

The compiler will not consider the virtual functions as inline functions, the functions that are considered as inline or not are purely compiler dependent.

Let us have a look into that:

First, we need to know about, What are virtual functions & how these are useful?

Virtual functions are used to achieve late binding or dynamic binding. They are used to achieve runtime polymorphism.

what is an inline function?

The whole idea behind the inline functions is that whenever an inline function is called, the code of the inline function gets substituted at the point of inline function call at compile time. These are useful at the place where we are using small functions which are frequently used and called in a program many times.

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.

 

#include <iostream>
using namespace std;
class A
{
public:
    virtual void Display()
    {
        cout << "I am A\n";
    }
};
class B: public A
{
public:
    void Display()
    {
        cout << "I am B\n";
    }
};

int main()

{
    A ocA;
    ocA.Display();
    A *ptr = new B();
    ptr->Display();
    return 0;
}

In the above program :

  
A ocA;
ocA.Display();

Here virtual function Display() is called through object of the class (it will be resolved at compile time) so it can be inlined.

  
A *ptr = new B();
ptr->Display();

Here virtual function is called through pointer, so it cannot be inline

Conclusion: The virtual functions are not inline functions.