C++ Virtual Function

Advertisements

C++ Virtual Function

Giving new implementation of base class method into derived class and the calling of this new implemented function with derived class's object is called function overriding.

Giving new implementation of derived class method into base class and the calling of this new implemented function with base class's object is done by making base class function as virtual function.

Virtual function is used in situation, when we need to invoke derived class function using base class pointer. We must declare base class function as virtual using virtual keyword preceding its normal declaration. The base class object must be of pointer type so that we can dynamically replace the address of base class function with derived class function. This is how we can achieve "Runtime Polymorphism".

If we doesn't use virtual keyword in base class, base class pointer will always execute function defined in base class.

Example of virtual function


       #include<iostream.h>
       #include<conio.h>

       class BaseClass
       {

              public:
               virtual void Display()
               {
                      cout<<"\n\tThis is Display() method of Base Class";
               }

               void Show()
               {
                      cout<<"\n\tThis is Show() method of Base Class";
               }

       };

       class DerivedClass : public BaseClass
       {

              public:
               void Display()
               {
                      cout<<"\n\tThis is Display() method of Derived Class";
               }

               void Show()
               {
                      cout<<"\n\tThis is Show() method of Derived Class";
               }

       };
       void main()
       {

              DerivedClass D;

              BaseClass *B;            //Creating Base Class Pointer
              B = new BaseClass;

              B->Display();            //This will invoke Display() method of Base Class
              B->Show();               //This will invoke Show() method of Base Class

              B=&D;

              B->Display();            //This will invoke Display() method of Derived Class
                                               //bcoz Display() method is virtual in Base Class

              B->Show();               //This will invoke Show() method of Base Class
                                               //bcoz Show() method is not virtual in Base Class

       }

   Output :

              This is Display() method of Base Class
              This is Show() method of Base Class
              This is Display() method of Derived Class
              This is Show() method of Base Class

Advertisement