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>
using namespace std;
class Shape{
protected:
float a, b;
public:
Shape(){}
virtual void display_area(){}
};
class Triangle: public Shape{
public:
Triangle(float x, float h): Shape(){
a = x;
b = h;
}
void display_area(){
cout<<0.5 * a * b;
}
};
class Rectangle: public Shape{
public:
Rectangle(float x, float h): Shape(){
a = x;
b = h;
}
void display_area(){
cout<<a * b;
}
};
int main(){
Rectangle rectangle(7, 5);
Triangle triangle(5, 8);
cout<<"Rectangle: ";rectangle.display_area();cout<<endl;
cout<<"Triangle: ";triangle.display_area();cout<<endl;
return 0;
}
Comments
Leave a comment