I'm trying to find a nice inheritance solution in C++.
I have a Rectangle class and a Square class. The Square class can't publicly inherit from Rectangle, because it cannot completely fulfill the rectangle's requirements. For example, a Rectangle can have it's width and height each set separately, and this of course is impossible with a Square.
So, my dilemma. Square obviously will share a lot of code with Rectangle; they are quite similar.
For examlpe, if I have a function like:
bool IsPointInRectangle(const Rectangle& rect);
it should work for a square too. In fact, I have a ton of such functions.
So in making my Square class, I figured I would use private inheritance with a publicly accessible Rectangle conversion operator. So my square class looks like:
class Square : private Rectangle
{
public:
operator const Rectangle&() const;
};
However, when I try to pass a Square to the IsPointInRectangle function, my compiler just complains that "Rectangle is an inaccessible base" in that context. I expect it to notice the Rectangle operator and use that instead.
Is what I'm trying to do even possible?
If this can't work I'm probably going to refactor part of Rectangle into MutableRectangle class.
Thanks.