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.
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.
#include<iostream.h>
using namespace std;
// Base class with virtual function
class Base {
int data1;
public:
Base ( int d1) { data1 = d1; }
virtual void print() { cout << "Base" << endl; }
};
// Derived class 1
class Derived1 : public Base {
int data2;
public:
Derived1(int d1, int d2) : Base (d1) { data2 = d2; }
void print() { cout << "Derived1" << endl; }
};
// Derived class 2
class Derived2 : public Base {
public:
Derived2(int d1) : Base (d1) { }
void print()
{ cout << "Derived2" << endl;
}
};
int main()
{ Base b(40);
Derived1 d1(10, 20);
Derived2 d2(30);
Base* ptr;
ptr=&d1;
ptr->print();
ptr=&d2;
ptr->print();
return 0;
}
OUTPUT:
Derived1
Derived2
Derived1
Derived2