Virtual function:

  • It is a run time polymorphism.
  • Base class and derived class have same function name and base class pointer isassigned address of derived class object then also pointer will execute base class function.
  • To execute function of derived class, we have to declare function of base class as virtual.
  • To declare virtual function just uses keyword virtual preceding its normal function declaration.
  • After making virtual function, the compiler will determine which function to execute at run time on the basis of assigned address to pointer of base class.

Rules for virtual function

1.The virtual functions must be member of any class.

2.They cannot be static members.

3.They are accessed by using object pointers.

4.A virtual function can be a friend of another class.

5.A virtual function in a base class must be defined, even though it may not be used.

6.If two functions with the same name have different prototypes, C++ considers them as overloaded functions, and the virtual function mechanism is ignored.

7.We cannot have virtual constructors, but we can have virtual destructors.

8.The derived class pointer cannot point to the object of base class

.9.When a base pointer points to a derived class, then also it is incremented or decremented only relative to its base type.Therefore we should not use this method to move the pointer to the next object.

10.If a virtual function is defined in base class, it need not be necessarily redefined in the derived class.In such cases, call will invoke the base class

Example:

#include<iostream.h>
#include<conio.h>
class Base
{
    protected:
        int a,b;
    public:
        virtual void getdata()
        {
            cout<<"Enter two value:";
            cin>>a>>b;
        }
        virtual void disp()
        {
            cout<<" The value are:"<<a<<" "<<b<<endl;
        }
};
class Sub : public Base
{
    protected:
        int c,d;
    public:
        virtual void getdata()
        {
            cout<<"Enter four value:";
            cin>>a>>b>>c>>d;
        }
        virtual void disp()
        {
            cout<<" The value are:"<<a<<" "<<b<<" "<<c<<" "<<d<<endl;
        }
};
void main()
{
    clrscr();
    Base *ptr;
    Base b;
    Sub s;
    ptr=&b;
    ptr->getdata();
    ptr->disp();
    ptr=&s;
    ptr->getdata();
    ptr->disp();
    getch();
}