I made this program to understand inheritance better.
Now that I'm at this basic level it's not really a problem but I can see this coming in the future and so I'm asking what's the best method to ask the user to insert the width and height of a rectangle (in this case).
The code I'm providing includes the simple way, by simply asking the user and inserting the number in a variable, then passing the variable to the setter inside the object (rect1).
I think when I will add up more shapes this can become a little confusing, is there a better way I can ask the user to input the number?
Since I'm asked to provide more context: I'm generally asking what's the best or a better method to ask input from the user that is going inside an object.
This is my version of it, that I think is good in this simple level but it will get messy with more shapes or generally more classes, I use 2 variable to ask for 2 dimensions, I will need 1 variable for every dimension and when I will create an object if I pass the wrong variable the program will work anyway, giving the wrong result.
Another way that I thought is insert an "askSomething" method in each class so that I don't need variables and every time a new object is created the io stream will be asked automatically. The "AskSomething" method is identical to a setter except it has cout and cin already inside
I don't really came up with other ideas.
The code I'm providing is a simple program that by asking height and width of a Rectangle calculate its Area, but of course by the class name Rectangle, the member names height and width and the method name getArea was pretty obvious.
main.cpp:
int main() {
Rectangle rect1;
int width, height;
std::cout << "Insert the width of the rectangle: ";
std::cin >> width;
std::cout << "Insert the height of the rectangle: ";
std::cin >>height;
rect1.setHeight(height);
rect1.setWidth(width);
std::cout << "The area of the rectangle is: " << rect1.getArea() << std::endl;
std::cout << "Drawing: " << std::endl;
std::cout << " ";
for (int i = 0; i < width+1; ++i) {
std::cout << "-";
}
std::cout << std::endl;
for (int j = 0; j < (height+1)/2; ++j) { // divided by 2 to have a better proportion
std::cout << "|";
for (int i = 0; i < width+1; ++i) {
std::cout << " ";
}
std::cout << "|";
std::cout << std::endl;
}
std::cout << " ";
for (int i = 0; i < width+1; ++i) {
std::cout << "-";
}
return 0;
}
Shape.h:
class Shape {
public:
int getWidth() const {
return width;
}
void setWidth(int width) {
Shape::width = width;
}
int getHeight() const {
return height;
}
void setHeight(int height) {
Shape::height = height;
}
protected:
int width, height;
};
Rectangle.h:
class Rectangle: public Shape {
public:
int getArea(){
return width*height;
}
};
Thanks to everyone! :)
What's the best way
leads to opinion based answers. Now your own suggestions to yourself are on the correct path. Please read codereview.stackexchange.com/help/how-to-ask \$\endgroup\$