Advertisement Area

Program #18: To Demonstrate the Virtual Function

C++ Language

#include<iostream.h>
#include<conio.h>
class base
{
    private:
    int x;
    public:
    base()
    {
        x=10;
    }
    virtual int getdata()
    {
        return(x);
    }
};
class derived:public base
{
    private:
    int y;
    public:
    derived()
    {
        y=20;
    }
    int getdata()
    {
        return(y);
    }
};
void main()
{
    clrscr();
    base*ptrobj;
    base baseobj;
    derived derivedobj;
    ptrobj=&baseobj;
    cout<<"Value of 'x' received by 'getdata()' function of base class is: "<<ptrobj->getdata();
    ptrobj=&derivedobj;
    cout<<"\nValue of 'y' received by 'getdata()' function of derived class is: "<<ptrobj->getdata();
    getch();
}


/*OUTPUT*/
Value of 'x' received by 'getdata()' function of base class is: 10
Value of 'y' received by 'getdata()' function of derived class is: 20