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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#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 :
1 2 3 |
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.
1 2 3 |
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.