Rectangle class using C++

Implement a rectangle class using C++. Rectangle class will provide rectangle objects. It will calculate area and perimeter. It should have

  • constructors
  • mutators (set methods)
  • accessors (get methods)
  • facilitators
  • inspector
  • destructor
#include<iostream>
using namespace std;
class Rectangle{
	private:
		int length;
		int breadth;
	public:
		Rectangle(int l=0, int b=0);
		Rectangle(const Rectangle& r);
		void setLength(int l);
		void setBreadth(int b);
		int getLength();
		int getBreadth();
		int area();
		int perimeter();
		bool isSquare();
		~Rectangle();
};
//Constructors
Rectangle::Rectangle(int l, int b){
	setLength(l);
	setBreadth(b);
}
Rectangle::Rectangle(const Rectangle& r){
	length = r.length;
	breadth = r.breadth;
}
//set methods - mutators
void Rectangle::setLength(int l){
	while(l<0){
		cout<<"Lenght is negative. Enter again : ";
	}
	length = l;
}
void Rectangle::setBreadth(int b){
	while(b<0){
		cout<<"Lenght is negative. Enter again : ";
	}
	breadth = b;
}
//get methods - accessors
int Rectangle::getLength(){
	return length;
}
int Rectangle::getBreadth(){
	return breadth;
}
//facilitators
int Rectangle::area(){
	return length*breadth;
}
int Rectangle::perimeter(){
	int perimeter = 2*(length+breadth);
	return perimeter;
}
//inspector
bool Rectangle::isSquare(){
	if(length==breadth) return true;
	else return false;
}
//destructor
Rectangle::~Rectangle(){
	cout<<"Destructor called"<<endl;
}
int main(){
	Rectangle r1;
	r1.setLength(20);
	r1.setBreadth(30);
	cout<<"Lenght of rectangle is "<<r1.getLength()<<endl;
	cout<<"Breadth of rectangle is "<<r1.getBreadth()<<endl;
	cout<<"Area of rectangle is "<<r1.area()<<endl;
	cout<<"Perimeter of rectangle is "<<r1.perimeter()<<endl;
	Rectangle r2(r1);
	r2.setBreadth(35);
	cout<<"Lenght of rectangle r2 is "<<r2.getLength()<<endl;
	cout<<"Breadth of rectangle r2 is "<<r2.getBreadth()<<endl;
	cout<<"Area of rectangle r2 is "<<r2.area()<<endl;
	cout<<"Perimeter of rectangle r2 is "<<r2.perimeter()<<endl;
	return 0;
}
output of the rectangle class program
output of the rectangle class program

Leave a Reply