Thursday, 27 November 2014

Does the virtual functions be inlined?

Is the virtual functions be inlined? Please explain with examples.

As of we know the functions that are available n 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 is purely compiler dependent.

Let us have a look into that:

First we need know about, What are virtual functions & how these are useful?
Virtual functions are used to achieve the late binding or dynamic binding. The virtual functions are used to achieve the runtime polymorphism.


Let us know about, what is an inline function?

The whole idea behind the inline functions is that whenever inline function is called code of 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 virtual function is called using base class reference or pointer it cannot be inlined (because call is resolved at runtime), but whenever called using the object (without reference or pointer) of that class, can be inlined because compiler knows the exact class of the object at compile time.
#include <iostream>
using namespace std;
class A
{
public:
    virtual void Disply()
    {
        cout << "I am A\n";
    }
};
class B: public A
{
public:
    void Disply()
    {
        cout << "I am B\n";
    }
};

int main()

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

In the above program
    A ocA;
    ocA.Disply();

Here virtual function Disply() is called through object of the class (it will be resolved at compile time) so it can be inlined.
    A *ptr = new B();
    ptr->Disply();
  Here virtual function is called through pointer, so it cannot be inline

Conclusion: The virtual functions are not inline functions.

No comments: