In: Computer Science
In need of assistance in C++ code:
Design and implement class Rectangle to represent a rectangle object. The class defines the following attributes (variables) and methods:
Now design and implement a test program to create two rectangle objects: one with default height and width, and the second is 5 units high and 6 units wide. Next, test the class methods on each object to print the information as shown below.
Sample run:
First object:
Height: 1 unit
Width: 1 unit
Area: 1 unit
Perimeter: 4 units
Second object:
Height: 5 unit
Width: 6 unit
Area: 30 units
Perimeter: 22 units
Thanks in advance!
#include <iostream>
using namespace std;
class Rectangle {
public:
// instance variables
double height;
double width;
// default constructor
Rectangle() { // need () for contructors
height = 1.0;
width = 1.0;
}
// ovarloaded constructor
Rectangle(double l, double w) {
height = l;
width = w;
}
// accessor methods/getters
double getHeight() {
return height;
}
double getWidth() {
return width;
}
// mutator/setter methods
void setHeight(double h) {
height= h;
}
void setWidth(double width) {
width = width;
}
double getArea() {
double area = height * width;
return area;
}
double getPerimeter() {
double per;
double length2 = height * 2;
double width2 = width * 2;
per = length2 + width2;
return per;
}
};
int main() {
double l,w;
cout<<"Enter height and length: ";
cin>>l;
cin>>w;
Rectangle *r1 = new Rectangle();
cout<<"First Object:\n";
cout<<"Height:
"<<r1->getHeight()<<" unit(s)"<<endl;
cout<<"Width:
"<<r1->getWidth()<<" unit(s)"<<endl;
cout<<"Area :
"<<r1->getArea()<<"unit(s)"<<endl;
cout<<"Perimeter :
"<<r1->getPerimeter()<<"unit(s)"<<endl;
Rectangle *r2 = new Rectangle(l, w);
cout<<"Second Object:\n";
cout<<"Height:
"<<r2->getHeight()<<" unit(s)"<<endl;
cout<<"Width:
"<<r2->getWidth()<<" unit(s)"<<endl;
cout<<"Area :
"<<r2->getArea()<<"unit(s)"<<endl;
cout<<"Perimeter :
"<<r2->getPerimeter()<<"unit(s)"<<endl;
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me