To understand the purpose of Virtual function, we should know the following concepts:
Abstract class:
It is defined as a class which contains atleast one pure virtual function and is not instantiated i.e. its object is not created. It is just inherited by the derived class. It only encompasses the basic attributes and methods that are common for all the classes that will inherit it.
Inheritance:
It is simply defined as reusing the existing attributes and methods in another class (derived class).
Static Binding:
By default, C++ compiler matches a function call with the correct function definition at compile time. This is called static binding.
Dynamic Binding:
When the compiler matches a function call with the correct function definition at run time; this is called dynamic binding. You declare a function with the keyword virtual if you want the compiler to use dynamic binding for that specific function.
Purpose:
The most prominent reason why a C++ virtual function will be used is to have a different functionality in the derived class.
Lets us understand it with an example of Area function which is used for circle, square and rectangle.
Class figure
{
Virtual void area()
{
Cout<<”----Area of different shapes -----”<<endl;
}
};
class circle : public figure
{
public:
float radius;
void area()
{
radius = 4;
cout<<”area of circle “ << 3.14*radius*radius;
}
};
class square : public figure
{
public:
int side;
void area()
{
side=4;
cout<<”\narea of sqaure “ << side*side;
}
};
class rectangle : public figure
{
public:
int l, w;
void area()
{
l=4; w=2;
cout<<”\narea of rectangle “ <area();//calls
}
};
void main()
{
figure *ptr;
ptr = new figure();
ptr->area();//calls area function of figure class.
ptr = new circle();
ptr->area();// calls area function of circle class
ptr = new square();
ptr->area(); // calls area function of square class
prt = new rectangle();
ptr->area();// calls area function of rectangle class
}
Output:
----Area of different shapes -----
area of circle 50.24
area of square 16
area of rectangle 8



