I have the following simple classes which model sets of points.
struct Shape
{
virtual bool contains(point x) const = 0;
}
typedef std::shared_ptr<Shape> ShapePtr;
struct Intersection : public Shape
{
Intersection(ShapePtr shape1, ShapePtr shape2):
shape1_(shape1),shape2_(shape2){}
ShapePtr shape1_;
ShapePtr shape2_;
bool contains(point x) const {return shape1_->contains(x) &&
shape2_->contains(x);}
}
ShapePtr intersect(ShapePtr shape1, ShapePtr shape2)
{
return std::make_shared<Intersection>(shape1, shape2);
}
so far so good. But suppose that I add a Shape
that is a Rectangle
:
struct Rectangle : public Shape
{
double x1_,x2_,y1_,y2_;
...
}
The original code works fine, but it can be improved using the fact that the intersection of two rectangles is a rectangle. That is, the intersect
function could return a pointer pointing to a Rectangle
.
How should I modify this code to accommodate for more such situations when I add more complicated shapes?