C++ program to implement virtual function


          /* FIND AREA OF TRIANGLE & RECTANGLE USING VIRTUAL FUNCTION */

#include<iostream.h>
#include<conio.h>
class shape
{
protected:
double x,y;
public:
void get_data(double i,double j=0)
{x=i;
y=j;
}
virtual void set_data(void)
{
cout<<"no area defined\n";
}};
class triangle:public shape
{
public:
void set_data(void)
{
cout<<"triangle with heigth '"<<x<<"' & base '"<<y<<"'\n";
cout<<"has area ="<<x*0.5*y<<"\n";
}};
class rectangle:public shape
{public:
void set_data(void)
{cout<<"\n\nrectangle with length '"<<x<<"' & breadth '"<<y<<"'\n";
cout<<"has area ="<<x*y<<endl;
}};
void main()
{ clrscr();
shape *p;
triangle t;
rectangle r;
p=&t;
p->get_data(10,5);
p->set_data();
p=&r;
p->get_data(5,8);
p->set_data();
getch();
}

Previous
Next Post »