Construct a class named Rectangle that has two double-precision data members nam
ID: 3860691 • Letter: C
Question
Construct a class named Rectangle that has two double-precision data members named length and width.
The class should have the following class functions:
a) A constructor with the default values of 1 for both length and width data members
b) An accessor function named showData() to show a rectangle's length and width
c) A mutator function named setData() to set the rectangle's length and width
d) A class function named perimeter() that calculates and displays the rectangle's perimeter
e) A class function named area() that calculates and displays the rectangle's area
Include the Rectangle class constructed in a working C++ program and exercise all functions.
Plz, use a C++ code
Explanation / Answer
#include<iostream>
using namespace std;
class Rectangle{
private:
double length;
double width;
public:
Rectangle(){
length = 1;
width = 1;
}
void showData(){
cout << "Length:" << length << endl;
cout << "Width:" << width << endl;
}
void setData(double len, double wid){
length = len;
width = wid;
}
void calculatePerimeter(){
cout << "Perimeter:" << 2*(length + width) << endl;
}
void calculateArea(){
cout << "Area:" << length * width << endl;
}
};
int main(){
Rectangle rt;
rt.showData();
rt.setData(20,30);
rt.showData();
rt.calculatePerimeter();
rt.calculateArea();
return 0;
}