WAP that defines a shape class with a constructor that gives value to width and height. The define two sub-classes triangle and rectangle, that calculate the area of the shape area (). In the main, define two variables a triangle and a rectangle and then call the area() function in this two varibles.
#include <iostream>
using namespace std;
class Shape
{
private:
double width, height;
public:
// constructor
Shape(double newWidth, double newHeight){
this->width=newWidth;
this->height=newHeight;
}
double getWidth() const
{
return width;
}
double getHeight() const
{
return height;
}
};
class Rectangle: public Shape
{
public:
Rectangle(double width, double height):Shape(width,height)
{
}
double area()
{
return (getWidth()*getHeight());
}
};
class Triangle: public Shape
{
public:
Triangle(double base, double height): Shape(base,height)
{
}
double area()
{
return (getWidth()*getHeight())/2.0;
}
};
int main ()
{
Rectangle rectangle(5.0,3.0);
Triangle triangle(2.0,5.0);
cout <<"Area of rectangle is: "<< rectangle.area() << endl;
cout <<"Area of triangle is: "<< triangle.area() << endl;
system("pause");
return 0;
}
Comments
Leave a comment