Virtual Function


Suppose you have derived a new class from the base class as shown below:
Class Base
{
Public:
Void display ()
{
Cout <<"Base Class";
}
};
Class Derive: public Base
{
Public:
Void display ()
{
Cout <<"Base Class";
}
};

     

In above example both base class and derived class contains same function display (). Since Derive class is publicly derived from base class the display () function of base class also becomes the member of derived class.
Now if you create an object of derived class and invoke the display () function it will invoke the base class version of the function. In such situation where both base and derive case contains same function we have to define that function as virtual in the base class.
In order to declare a function as virtual we have to precede the function declaration with virtual keyword.
When we use the same member function in both base and derived class then the function in base class is made virtual.
Once we define the common function as virtual in the base class we need to declare a pointer of type base class. If base class pointer contains the address of base class object then base class function is invoked and if base class pointer contains the address of derived class object then derived class function is invoked.
Thus compiler will select appropriate version of the function at run time based on address contained in the base class pointer.

#include <iostream.h>
class Base
{
          int x;
          public:
          virtual void Display ()
          {
                   cout <<“Base”;
          }
};
class Derive: public Base
{
          int y;
          public:
          void Display ()
          {
                   cout <<“Derived”;
          }
};
void main()
{
          Base B1;
          Derive D1;
          Base * ptr;
          ptr = &B1;
          ptr->Display (); // call base class member function
          ptr = &D1;
         ptr->Display (); // call derived class member function
}


Rules for Defining Virtual Function


o If prototype of base class and derived class functions are identical then and only then you can declare a function as virtual in base class.
o Virtual function must be member function of a class.
o You can not declare constructor as a virtual in base class.
o Virtual function can not be static.
o In order to access virtual function we must have to use pointer of base class.

Download Projects


Download Programs