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
Description:
This task requires the creation of a class called Rectangle
with double fields for length and width. The class should provide set methods for both fields, a constructor that initializes the dimensions, and methods to compute the area and perimeter. Next, you will implement a Square
class that inherits from Rectangle
. The Square
class should ensure that both its dimensions remain equal at all times by overriding the set methods. Separate header and source files must be created for each class.
Explanation:
The Rectangle
class represents a basic geometric rectangle and provides encapsulation for its properties and behaviors. It includes methods to modify its length and width, and to calculate its area and perimeter.
The Square
class extends Rectangle
and enforces the property that both sides must always be equal, ensuring the integrity of the square shape. To do this, it overrides the setLength
and setWidth
methods so that setting either dimension updates both.
By separating the classes into .hpp
and .cpp
files, the program follows good C++ programming practices, making the code more modular and maintainable.