I've been trying to understand C++ inheritance and polymorphism a little bit better. But I'm having a really hard time getting this to work.
I have a base class called Shape. I have Rectangle that is child of Shape. And Square that is child of Rectangle.
Shape has no area. Rectangle and Square have area equal to width*height.
Setting width and height for Rectangle is independent. In the case of Square, when setting width or height, the function will set both attributes to the same value. Unfortunately that is not what is happening if I try to use polymorphism by creating a Square on a Rectangle.
shapes.hpp:
#ifndef SHAPES_H
#define SHAPES_H
// Base class
class Shape {
public:
virtual void setWidth(int w);
virtual void setHeight(int h);
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape {
public:
int getArea();
};
class Square: public Rectangle {
public:
void setWidth(int w) override;
void setHeight(int h) override;
};
#endif /* SHAPES_H */
shapes.cpp:
#include "shapes.hpp"
// Base class
void Shape::setWidth(int w) {
width = w;
}
void Shape::setHeight(int h) {
height = h;
}
// Derived class
int Rectangle::getArea() {
return (width * height);
}
// Overloading
void Square::setWidth(int w) {
width = w;
height = w;
}
void Square::setHeight(int h) {
width = h;
height = h;
}
Testing the getArea() functions:
Shape rect = Rectangle();
rect.setHeight(7);
rect.setWidth(5);
//I had to cast the Rectangle so it would be able to call getArea()
cout << "Total rectangle area (w5xh7): " << ((Rectangle*)&rect)->getArea() << endl;
Rectangle square = Square();
square.setHeight(7);
square.setWidth(5);
//I would like to be able to call Square's getArea() without having to cast it.
cout << "Total square area (w5xh7): " << square.getArea() << endl;
I had to cast the Rectangle so it would be able to call getArea(). I would like to be able to call Square's getArea() without having to cast it. Is that possible?
Thank you.