Write a class called Rectangle with double fields for its length and width. It s
ID: 3760557 • Letter: W
Question
Write a class called Rectangle with double fields for its length and width. It should have set methods for both fields. It should have a constructor that takes two double parameters and passes them to the set methods. It should also have a method called area that returns the area of the Rectangle and a method called perimeter that returns the perimeter of the Rectangle.
Write a class called Square that inherits from Rectangle. It should have a constructor that takes one double parameter and passes it to the base class constructor for both parameters (the body of the constructor will be empty). Square will also need to override the setLength() and setWidth() functions of its base class such that if either of its dimensions is set to a new value, then both of its dimensions will be set to that new value (so that it remains a square).
Hint: you can have the overridden versions call the versions in the base class.
The files must be called: Rectangle.hpp, Rectangle.cpp, Square.hpp and Square.cpp
Explanation / Answer
#include<iostream.h>
#include<conio.h>
class Rectangle
{
public:
double wid, len;
void setwidth(double w)
{
wid=w;
}
void setlength(double l)
{
len=l;
}
Rectangle(double w, double l)
{
setwidth(w);
setlength(l);
}
double area()
{
return wid*len;
}
double perimeter()
{
return 2*(wid*len);
}
};
class Square:public Rectangle
{
public:
Square(double p)
:Rectangle(p,p)
{
}
void setwidth(double w)
{
wid=w;
}
void setlength(double l)
{
len=l;
}
};
void main()
{
Square unit(12);
double a=unit.area();
double per=unit.perimeter();
cout<<"Area is "<<a;
cout<<"Perimeter is "<<per;
getch();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.