VIRTUAL FUNCTION

A virtual function is a member function that is declared within a base class and redefined by a derived class. To create virtual function, precede the function’s declaration in the base class with the keyword virtual. When a class containing virtual function is inherited, the derived class redefines the virtual function to suit its own needs.
Base class pointer can point to derived class object. In this case, using base class pointer if we call some function which is in both classes, then base class function is invoked. But if we want to invoke derived class function using base class pointer, it can be achieved by defining the function as virtual in base class, this is how virtual functions support run-time polymorphism.

Consider following program code:


Class Base
{
        int a;
        public:
        Base()
        {
                 a = 1;
        }
        virtual void show()
        {
                 cout <<a;
        }
};

Class Drive: public Base
{
         int b;
         public:
         Drive()
         {
                b = 2;
         }
         virtual void show()
         {
                cout <<b;
         }
};

int main()
{
           Base *pBase;
           Drive oDrive;
           pBase = &oB;
           pBase->show();
           return 0;
}

Output is 2

since pBase points to object of Drive and show() is virtual in base class Base.

Comments

Popular Posts