On Part 3 of the ultimate C++ course on episode 7 of classes, a code is made that makes the compiler print
“Constructing a Rectangle” << endl
<< (width value)
but for some reason whenever I run this code
it says my width’s value is 0 despite me setting it to 50.
I tried to make it show me my height’s value but that didn’t work.
and in a certain part of the code below it forces any negative values to cause an error message but I tried that and even that failed.
the code is as follows in three sections
main.cpp code
#include
#include “Rectangle.h”
using namespace std;
int main() {
Rectangle rectangle{50, 20};
cout << rectangle.getWidth();
return 0;
}
Rectangle.cpp code
#include “Rectangle.h”
#include
using namespace std;
int Rectangle::getArea() const {
return width * length;
}
void Rectangle::draw() const {
cout << “Drawing a rectangle” << endl;
cout << “Dimensions:” << width << ", " << length;
}
int Rectangle::getWidth(){
return width;
}
void Rectangle::setWidth(int Width) {
if (width < 0)
throw invalid_argument(“Width”);
this->width = width;
}
int Rectangle::getHeight() const {
return length;
}
the below is still the code to rectangle.cpp
void Rectangle::setHeight(int height) {
if (length < 0)
throw invalid_argument(“Length”);
(*this).length = length;
}
Rectangle::Rectangle(int width, int length) {
cout << “Constructing a rectangle” << endl;
setWidth(width);
setHeight(length);
}
Rectangle.h code
#ifndef ADVANCED_RECTANGLE_H
#define ADVANCED_RECTANGLE_H
class Rectangle {
public:
Rectangle(int width, int length);
void draw() const;
int getArea() const;
int getWidth();
void setWidth(int width);
int getHeight() const;
void setHeight(int height);
private:
int width{};
int length{};
};
#endif //ADVANCED_RECTANGLE_H