Rectangle Class in C++

Posted by Samath
  1567
January 01, 2015

 

Design a class named Rectangle to represent a rectangle.  The class contains:

- Two double data fields named width and height that specify the width and height of the rectangle.  The    default values are 1 for both width and height.

 - A no-arg constructor that creates a rectangle with default values.

 - A constructor that creates a rectangle with the specified width and height.

 - A method named getArea() that returns the area of this rectangle.

 - A method named getPerimeter() that returns the perimeter.

 

Solution:

#include <iostream>
 
using namespace std;

class Rectangle
{
public:
	Rectangle();
	double getArea();
	double getPerimeter();
	double getWidth();
	double getHeight();
	void setWidth(double w);
	void setHeight(double h);
	Rectangle (double w, double h);

private:
	double width;
	double height;

};


double Rectangle::getPerimeter()
{
	return 2 * (width + height);
}

double Rectangle::getArea()
{
	return width * height;
}

double Rectangle::getWidth()
{
	return width;
}

double Rectangle::getHeight()
{
	return height;
}

void Rectangle::setWidth(double w)
{
	width = w;
}

void Rectangle::setHeight(double h)
{
	height = h;
}

Rectangle::Rectangle (double w, double h)
{
	width = w;
	height = h;
}

Rectangle::Rectangle()
{
	width = 1;
	height = 1;
}

 
int main(int argc, char *argv[])
{
	Rectangle myRectangle1(40, 20);
	Rectangle myRectangle2(20,10);

	cout<<"Rectangle 1 Perimeter: "<<myRectangle1.getPerimeter();
	cout<<"\nRectangle 1 Area: "<<myRectangle1.getArea();

	cout<<"\n\nRectangle 2 Perimeter: "<<myRectangle2.getPerimeter();
	cout<<"\nRectangle 2 Area: "<<myRectangle2.getArea();


	return 0;	
}