I did the first part of the assignment but I\'m not sure how ot make the Square
ID: 3669068 • Letter: I
Question
I did the first part of the assignment but I'm not sure how ot make the Square class.
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
Rectangle.hpp
#ifndef Rectangle_hpp
#define Rectangle_hpp
class Rectangle
{
private:
double width;
double length;
public:
Rectangle(double length2, double width2);
void setLength(double length2);
void setWidth(double width2);
double getLength();
double getWidth();
double area() ;
double perimeter() ;
};
#endif
Rectangle.cpp
#include "Rectangle.hpp"
#include <iostream>
using namespace std;
Rectangle::Rectangle(double length2, double width2)
{
setLength(length2);
setWidth(width2);
}
void Rectangle::setLength(double length2)
{
length = length2;
}
void Rectangle::setWidth(double width2)
{
width = width2;
}
double Rectangle::getLength()
{
return length;
}
double Rectangle::getWidth()
{
return width;
}
double Rectangle::area()
{
return length * width;
}
double Rectangle::perimeter()
{
return 2*(length + width);
}
Explanation / Answer
I have written the code for square class.
Square.hpp
#ifndef Rectangle_hpp
#define Rectangle_hpp
class Square: public Rectangle
{
private:
double side;
public:
Square(double side);
void setLength(double length2);
void setWidth(double width2);
double getLength();
double getWidth();
double area() ;
double perimeter() ;
};
#endif
Square.cpp
#include "Square.hpp"
#include <iostream>
using namespace std;
Square::Square(double side)
{
Rectangle(side,side);
setLength(side);
setWidth(side);
}
void Square::setLength(double length2)
{
side = length2;
}
void Square::setWidth(double width2)
{
side = width2;
}
double Square::getLength()
{
return side;
}
double Square::getWidth()
{
return side;
}
double Square::area()
{
return side * side;
}
double Square::perimeter()
{
return 4*(side);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.