ISourceCode

Make the frequent cases fast and the rare case correct

Implementation of Virtual Function in C++

Virtual Function uses a Virtual table or vtable.A vtable is constructed if a function of a class is declared as virtual and stores the addresses of the virtual functions of the class. Behind the scene the compiler introduces a vptr variable in all classes that point to the vtable of that class. If a virtual function in the derived class is not overridden, the vtable of derived class stores the address of function in the parent class, this is illustrated by example below. vtable helps resolve the address of the function. Dynamic binding is thus achieved through this vtable mechanism. Virtual function is a frequently used OOP concept and illustrates the polymorphism feature of OOP.

#include <iostream> 
using namespace std; 
 
class Base{ 
public: 
  virtual void sample(){ 
    cout << "This is Base class virtual function\n"; 
  } 
}; 
 
class Derived1 : public Base { 
public: 
  void sample() { 
    cout << "Derive class 1 sample function has been invoked\n";//redefine sample() for Derived1 
  } 
}; 

class Derived2 : public Base { 
public: 
  void sample() { // redefine sample() for Derived2 
    cout << "Derive Class 2 sample function has been invoked\n"; 
  } 
};

class Derived3 : public Base { 
// sample() not defined
}; 
 
int main() 
{ 
  Base baseobject; 
  Base *p; 
  Derived1 Derived1object; 
  Derived2 Derived2object;
  Derived3 Derived3object; 
 
  p = &baseobject; 
  p->sample();  // access Base class sample() 
 
  p = &Derived1object; 
  p->sample(); // access Derived1 class sample() 
 
  p = &Derived2object; 
  p->sample(); // access Derived2 class sample() 

  p = &Derived3object; 
  p->sample(); /* access Base class sample() because 
               Derived3 does not redefine it */ 
 
  return 0; 
}

OUTPUT:

laptop:~/code$ ./a.out
This is Base class virtual function
Derive class 1 sample function has been invoked
Derive Class 2 sample function has been invoked
This is Base class virtual function

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: