Write a class called Rectangle with double fields for its length and width. It s
ID: 3760313 • 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
Rectangle.hpp
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle
{
public:
Rectangle(float width, float length);
float get_area();
float get_perimeter();
private:
float width, length;
};
#endif
Rectangle.cpp
#include "Rectangle.hpp"
#include "Square.hpp"
#include <iostream>
using namespace std;
Rectangle::Rectangle(float width, float length){
width = width;
length = length;
}
float Rectangle::get_area(){
return width*length;
}
float Rectangle::get_perimeter(){
return 2*(length+width);
}
Square.hpp
#ifndef SQUARE_H
#define SQUARE_H
class Square : public Rectangle
{
public:
Square(float side);
private:
};
#endif
Square.cpp
#include "Rectangle.hpp"
#include "Square.hpp"
#include <iostream>
using namespace std;
Square::Square(float side)
{
Rectangle r(side,side);
}
Main
#include "Rectangle.hpp"
#include "Square.hpp"
#include <iostream>
using namespace std;
int main()
{
Rectangle rectangleObject(2,5);
Square squareObject(5);
cout << "The area of the rectangle is" << rectangleObject.get_area() << ' ';
cout << "The perimeter of the rectangle is " << rectangleObject.get_perimeter() << ' ';
cout << "The area of the square is " << squareObject.get_area() << ' ';
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.