Create a base class called Shape which has two double type values. Use member functions get()
and set() to get and set the values. Use a virtual function display_area() to display the area. Derive
two specific classes called Triangle and Rectangle from the base class Shape. Redefine
display_area() in the derived classes. Write a program to display the rectangle or triangle area.
#include <iostream>
#include <string>
using namespace std;
class Shape
{
protected:
//has two double type values.
double height,base;
public:
//constructor to assign initial values to height and base
Shape(){
this->height=0;
this->base=0;
}
void set(){
cout<<"Enter height: ";
cin>>height;
cout<<"Enter base: ";
cin>>base;
}
//get() function to get values
double geHeight(){
return height;
}
double geBase(){
return base;
}
//declaration of virtual function display_area()
virtual void display_area(){}
};
//class triangle inheriting class Shape
class Triangle : public Shape
{
public:
//redefining function display_area()
void display_area()
{
cout<<"Height: "<<height<<"\n";
cout<<"Base: "<<base<<"\n";
cout<<"Area of Triangle = "<<(height*base)/2;
}
};
//class Rectangle inheriting class Shape
class Rectangle : public Shape
{
public:
//redefining function display_area()
void display_area()
{
cout<<"Side a: "<<height<<"\n";
cout<<"Side b: "<<base<<"\n";
cout<<"Area of Rectangle = "<<(height*base);
}
};
void main(){
Shape *shape;
Triangle triangle;
triangle.set();
shape=▵
shape->display_area();
Rectangle rectangle;
cout<<"\n\n";
rectangle.set();
shape=&rectangle;
shape->display_area();
cout<<"\n\n";
system("pause");
}
Comments
Leave a comment