C++ Virtual Function

Polymorphism refers to the property by which objects belonging to different classes are able to respond to the same message but in different forms. When there are C++ functions with the same name in both superclass as well as a subclass, virtual functions gives programmer capability to call a member function of a different class by the same function call based upon different context. This feature is known as polymorphism which is one of the important features of OOP. The pointer is also one of the key aspects of C++ language similar to that of C. In this chapter, we will be dealing with virtual functions and pointers of C++.

What is Virtual Function?

A virtual function is a special form of member function that is declared within a base class and redefined by a derived class. The keyword virtual is used to create a virtual function, precede the function's declaration in the base class. If a class includes a virtual function and if it gets inherited, the virtual class redefines a virtual function to go with its own need. In other words, a virtual function is a function which gets override in the derived class and instructs the C++ compiler for executing late binding on that function. A function call is resolved at runtime in late binding and so compiler determines the type of object at runtime.

Program for Virtual Function:

Example:
#include 
using namespace std; 

class b
{
public:
virtual void show()
{
cout<<"\n  Showing base class....";
}
void display()
{
cout<<"\n  Displaying base class...." ;
}
};

class d:public b
{
public:
void display()
{
cout<<"\n  Displaying derived class....";
}
void show()
{
cout<<"\n  Showing derived class....";
}
};

int main()
{
b B;
b *ptr;
cout<<"\n\t P points to base:\n" ; ptr=&B; ptr->display();
ptr->show();
cout<<"\n\n\t P points to drive:\n"; d D; ptr=&D; ptr->display();
ptr->show();
}
Program Output:
     P points to base:

Displaying base class....
Showing base class....
   
     P points to drive:
      
Displaying base class....
Showing derived class....