Answer to Question #211676 in C++ for GAJERA ASHISH

Question #211676

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.


1
Expert's answer
2021-06-29T00:13:08-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS