Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a base class Shape, and drived classes Line Segment, Arc, B-spline,... I want to find the intersection point between these shapes. I would like:

Shape* a = new LineSegment();
Shape* b = new Arc();

bool did_intersect = a->Intersect(b);

I don't like this design in Intersect:

bool LineSegment(Shape* s) {
  Arc* arc = dynamic_cast<Arc*>(s);
  if (NULL != arc)
    return LineSegmentArcIntersection(this, arc);

  BSpline* bspline = dynamic_cast<BSpline*>(s);
  if (NULL != bspline)
    return LineSegmentBSplineIntersection(this, bspline);

So, What design pattern is best suitable with this context?

share|improve this question
Why don't you like this design? – Robert Harvey Oct 27 '10 at 15:35
I think this design violate Open-Closed Principle. This structure is repeated over all drived classes. – Hieu Phan Oct 27 '10 at 16:23

I think you are looking for double dispatch or multiple dispatch.

Btw., this question is better suited for StackOverflow.

share|improve this answer
Effective C++ by Scott Meyers has a great article on double dispatch talking at great detail on how to implement it also! – brainydexter Mar 22 '12 at 13:47
Could you please answer… ? – Lijo Jul 11 '12 at 6:48

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.