I am trying to find good inheritance in C ++.
I have a Rectangle class and a square class. The Square class cannot publicly inherit a Rectangle, because it cannot fully comply with the rectangle requirements. For example, a rectangle can have a width and a height, each of which is set separately, and this, of course, is impossible with a square.
So, my dilemma. The square will obviously share a lot of code with the Rectangle; they are very similar.
For example, if I have a function like:
bool IsPointInRectangle(const Rectangle& rect);
It should work on the square. In fact, I have a ton of such features.
Thus, when creating the Square class, I decided to use private inheritance with the public Rectangle transform operator. So my square class looks like this:
class Square : private Rectangle { public: operator const Rectangle&() const; };
However, when I try to pass the square to the IsPointInRectangle function, my compiler simply complains that, in this context, "The rectangle is an inaccessible base." I expect him to notice the Rectangle operator and use it instead.
Am I trying to make it even possible?
If that doesn't work, I'm probably going to refactor the Rectangle part into a MutableRectangle class.
Thanks.
c ++ inheritance reference
Imbue
source share