What is Virtual Functions in C++

What is a virtual function?
One of the most talked about feature of object oriented programming. We have two types of polymorphism in C++. One is compile-time and the other is Run-time.
  • Virtual function is a use to achieve run-time polymorphism.
  • Refers to performing the same operation in a hierarchy of classes. Typically used in scenarios where the base class pointer is used to hold derived class objects and perform the same operation. See the example below.
  • When a virtual functions is called on a base class pointer the compiler decides to defer the decision on which function to call until the program is running thereby doing late binding.
  • The actual function called at run-time depends on the contents of the pointer and not the type.
  • Internally the compiler creates a Vtable for each class which has virtual functions or derived from base class.
  • Addresses of virtual functions are placed in the Vtable . If a virtual function is not redefined in the derived class, the base class function address is used in Vtable .
  • When objects are created compiler also places a VPTR pointing to starting address of Vtable using which the correct function is invoked.
EXAMPLE: Demonstrate the late binding using virtual functions

using namespace std;

// Base class with virtual function
class Base {
int data1;
Base ( int d1) { data1 = d1; }
virtual void print() { cout << "Base" << endl; }

// Derived class 1
class Derived1 : public Base {
int data2;
Derived1(int d1, int d2) : Base (d1) { data2 = d2; }
void print() { cout << "Derived1" << endl; }

// Derived class 2
class Derived2 : public Base {
Derived2(int d1) : Base (d1) { }
void print()
{ cout << "Derived2" << endl;
int main()
{ Base b(40);
Derived1 d1(10, 20);
Derived2 d2(30);
Base* ptr;
return 0;

Popular posts from this blog


HSC Exam Time Table 2013 Arts, Commerce, Science

What are cookies and its types? Where are cookies used?