For the Polygon base class below, write a constructor that initializes the the w
ID: 3634801 • Letter: F
Question
For the Polygon base class below, write a constructor that initializes the the width and height. Then write a Rectangle derived class, and a Triangle derived class with public functions that calculates the area. Note that the rectangle and triangle class inherit the constructor from the Polygon base class. Now in main(), declare objects rect and triag of type Rectangle and Triangle. Print the areas of rect(3,4) and triag(3,4)class CPolygon
{
protected: int width, height;
public: void set_values (int a, int b) { width=a; height=b;}
};
Explanation / Answer
Please Rate:Thanks
#include<iostream.h>
class CPolygon{
protected:int width,height;
public:
void set_values(int a,int b){
width=a;
height=b;
}
};
class Rectangle:public CPolygon{
public:
Rectangle(int a,int b)
{
set_values(a,b);
}
void area(){
cout<<" Area of rectangle "<<width*height;
}
};
class Triangle:public CPolygon{
public:
Triangle(int a,int b)
{
set_values(a,b);
}
void Area(){
cout<<" Area of Triangle "<<0.5*width*height;
}
};
void main()
{
Rectangle rect(3,4);
Triangle tri(3,4);
rect.area();
tri.Area();
}
--------------------------------------
Output: