Virtual Functions

Virtual Functions

What is Virtual Functions in C++?

Explanation

Virtual Function is a function that is declared within a base class and redefined in the derived class. Virtual functions are declared by preceding the class declaration with a keyword “virtual”. When a virtual function is declared C++ decides to execute a function based on the type of object pointed by the base pointer and not on the type of pointer.

Example :

#include class Bclass
{
public:
void disp() { cout << " BASE BASEn" ; }
virtual void sh() { cout << "base basen"; }
}; class Dclass : public Bclass
{
public:
void disp() { cout << "DERIVED DERIVEDn"; }
void sh() { cout << "derived derivedn"; }
}; int main()
{
Bclass B;
Dclass D;
Bclass *ptr;
cout << "ptr points to base classn" ;
ptr = &B;
ptr->disp();
ptr->sh();
cout << "ptr points derived classn";
ptr = &D;
ptr->disp();
ptr->sh();
return 0;
}

Result :

ptr points to base class
BASE BASE
base base
ptr points derived class
BASE BASE
derived derived

In the above example, the base ptr is used point the object D. Since the “sh()” function has a derived version in the form of a virtual function, it displays the base class version of “sh()”.





Leave a Reply

Your email address will not be published. Required fields are marked *