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 num1;
float num2;
public:
void setNum1(float n1){
num1=n1;
}
void setNum2(float n2){
num2=n2;
}
float getNum1(){
return num1;
}
float getNum2(){
return num2;
}
virtual void display_area(){
cout<<"Area: "<<getNum1()*getNum2()<<endl;
}
};
class Triangle: public Shape{
public:
virtual void display_area(){
cout<<"Area of the Triangle: "<<0.5*getNum1()*getNum2()<<endl;
}
};
class Rectangle: public Shape{
public:
virtual void display_area(){
cout<<"Area of the Rectangle: "<<getNum1()*getNum2()<<endl;
}
};
int main()
{
Triangle t1;
t1.setNum1(5);
t1.setNum2(7);
t1.display_area();
Rectangle r1;
r1.setNum1(15);
r1.setNum2(10);
r1.display_area();
return 0;
}
Comments
Leave a comment