using c++ Write the definition for a class called Rectangle that has int data me
ID: 3914098 • Letter: U
Question
using c++
Write the definition for a class called Rectangle that has int data members length and width.
Define accessor and mutator functions.
Define two constructors – i. default and ii. Constructor with two parameters.
Define intperimeter() to calculate and return the perimeter of the rectangle, int area() to calculate and return the area of the rectangle. void show() to display the output.
Overload the equality operator ==, post increment operator++ as member functions to check if two rectangle objects (width and length) are same or not and to increase length and width.
Test your program by user given input for length and width.
Explanation / Answer
#include<iostream>
using namespace std;
class Rectangle
{
int length,width;
public:
//constructor
//default...sets default values
Rectangle()
{
length = 10;
width = 5;
}
//parameter constructor
Rectangle(int l,int w)
{
length = l;
width =w;
}
//accessors & mutators
int getLength()
{
return length;
}
int getWidth()
{
return width;
}
void setLength(int l)
{
length =l;
}
void setWidth(int w)
{
width =w;
}
//perimeter method
int perimeter()
{
return 2*(length+width);
}
//area method
int area()
{
return (length*width);
}
//++ operator over loading
void operator ++()
{
length++;
width++;
}
//== operator over loading
bool operator ==(const Rectangle &r)
{
//cout<<this->length<<" "<<r.length<<endl;
//cout<<this->width<<" "<<r.width<<endl;
if((this->length==r.length) && (this->width==r.width))
return true;
return false;
}
///method to show rectangel contents
void show()
{
cout<<" Rectangle---------- ";
cout<<"Length: "<<length<<endl;
cout<<"Width: "<<width<<endl;
cout<<"---------------------- ";
}
};
//testing method
int main()
{
Rectangle *r = new Rectangle();
Rectangle *p = new Rectangle(5,2);
Rectangle *q = new Rectangle(4,1);
cout<<"Rectangle 1: ";
r->show();
cout<<"Rectangle 2: ";
p->show();
cout<<"Rectangle 3: ";
q->show();
//testing ++ operator over loading ...method
++*q;
cout<<"Rectangle 3: after applying ++ operator ";
q->show();
//testing two objects equal or not..using == operator overloading method...
if(*p==*q)
cout<<"Rectangle 2 and 3 are equal ";
else
cout<<"Rectangle 2 and 3 are not equal ";
return 0;
}
output:
Rectangle 1:
Rectangle----------
Length: 10
Width: 5
----------------------
Rectangle 2:
Rectangle----------
Length: 5
Width: 2
----------------------
Rectangle 3:
Rectangle----------
Length: 4
Width: 1
----------------------
Rectangle 3: after applying ++ operator
Rectangle----------
Length: 5
Width: 2
----------------------
Rectangle 2 and 3 are equal
Process exited normally.
Press any key to continue . . .
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.