Aim: To implement a program to find area of rectangle, surface area of box and volume of box using virtual functions.
Code:
class rect
{
double l,b;
public:
virtual void getdata();
virtual void area();
};
void rect::getdata()
{
cout<<"Enter the length and breadth of rectangle:\n";
cin>>l>>b;
}
void rect::area()
{
cout<<"Area of rectangle = "<
}
class box:public rect
{
double l,b,h;
public:
void getdata();
void area();
void volume();
};
void box::getdata()
{
cout<<"\nEnter the length, breadth and height of the box:\n";
cin>>l>>b>>h;
}
void box::area()
{
cout<<"Surface area of the box = "<<2*(l*b+b*h+l*h)<<" sq. units\n";
}
void box::volume()
{
cout<<"Volume of the box = "<
}
void main()
{
rect r,*ptr;
box b;
clrscr();
ptr=&r;
ptr->getdata();
ptr->area();
ptr=&b;
ptr->getdata();
ptr->area();
((box *)ptr)->volume();
getch();
}
Output:
Enter the length and breadth of rectangle:
10
15
Area of rectangle = 150 sq. units
Enter the length, breadth and height of the box:
5
12
6
Surface area of the box = 324 sq. units
Volume of the box = 360 cu. units