Inline virtual function in C++

C++Server Side ProgrammingProgramming

Virtual functions in C++ use to create a list of base class pointers and call methods of any of the derived classes without even knowing kind of derived class object. Virtual functions are resolved late, at the runtime.

The main use of the virtual function is to achieve Runtime Polymorphism. The inline functions are used to increase the efficiency of the code. The code of inline function gets substituted at the point of an inline function call at compile time, whenever the inline function is called.

Whenever a virtual function is called using base class reference or pointer it cannot be inlined, 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.

Example Code

 Live Demo

using namespace std;
class B {
      virtual void s() {
         cout<<" In Base \n";

class D: public B {
      void s() {
         cout<<"In Derived \n";

int main(void) {
   B b;
   D d; // An object of class D
   B *bptr = &d;// A pointer of type B* pointing to d
   b.s();//Can be inlined as s() is called through object of class
   bptr->s();// prints"D::s() called"
   //cannot be inlined, as virtualfunction is called through pointer.
   return 0;


In Base
In Derived
Published on 03-Apr-2019 14:23:15