I am 1st semester computer science student having trouble on this problem.
Write a class called Rectangle with double fields for its length and width, set methods for both fields, a constructor that takes two double parameters and passes them to the set methods. It should include a method called area and perimeter area of the Rectangle and 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.
I am using Code::Blocks and C++ as the language.
Rectangle.hpp
#include <iostream>
using namespace std;
#include <cmath>
#ifndef Rectangle_HPP
#define Rectangle_HPP
class Rectangle
{
protected:
double length;
double width;
public:
Rectangle();
Rectangle(double,double);
double area();
double perimeter();
void setLength(double);
void setWidth(double);
};
#endif
Rectangle.cpp
#include <iostream>
using namespace std;
#include <cmath>
#include "Rectangle.hpp"
Rectangle::Rectangle(double l, double w)
{
length = l;
width = w;
}
double Rectangle::area()
{
return (width * length);
}
double Rectangle::perimeter()
{
return (2*(width + length));
}
void Rectangle::setLength(double l)
{
length = l;
}
void Rectangle::setWidth(double w)
{
width = w;
}
Square.hpp
#include <iostream>
using namespace std;
#include <cmath>
#include "Rectangle.hpp"
#ifndef Square_HPP
#define Square_HPP
class Square: public Rectangle
{
public:
Square();
Square(double);
void setLength(double);
void setWidth(double);
};
#endif
Square.cpp
#include <iostream>
using namespace std;
#include <cmath>
#include "Rectangle.hpp"
#include "Square.hpp"
Square::Square(double side){}
void Square::setLength(double side)
{
length = side;
width = side;
}
void Square::setWidth(double side)
{
length = side;
width = side;
}
int main()
{
return 1;
}
I have tested the Rectangle.hpp and the Rectangle.cpp by themselves with a main method, and they seem to work fine, but I am having trouble with the Square.hpp and Square.cpp. Is there anything that you see that I am obviously missing. The undefined reference to Rectangle::Rectangle is the only error that Code::Blocks is returning to me so far. It says the error is in the Square.cpp file. I have made sure that all four files are part of the same project, so that shouldn't be the issue.