Question

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?

Was it helpful?

Solution

You probably want MultiMethods. Specifically, you want runtime-dispatch on actual type.

Here's a post about them: "type-switch" construct in C++11

BTW: As you are always using std::shared_ptr with all objects derived from Shape, consider using std::enable_shared_from_this.

Also, you might want to create a bounding box and check for empty intersection. As an added optimisation, add an empty shape (static Singleton object). Shape itself is a good type for it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top