1

I have what I think should be a simple design but I'm having trouble coming up with a solution that doesn't involve RTTI (or methods that return the type). I have a generic Shape interface that contains a pure virtual draw method only. Elsewhere in my program, I have a vector of pointers to Shapes, and I invoke the draw call on each Shape.

Now, I would like to extend the functionality of Shape to allow Shapes to compare to one another and return whether or not they overlap. Obviously, this code depends on the specific type of the subclass of Shape -- that is, the code to determine whether two circles overlap is different than the code to determine whether a circle and a rectangle overlap. Right now, I am simply using typeid followed by a dynamic cast to dispatch two objects to the correct overlap code, which seems very kludgy. Is there a pattern or technique I can use to avoid the use of typeid and static_casts?

  • 1
    What about template classes and [static polymorphism](http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)? – πάντα ῥεῖ Aug 17 '14 at 20:58
  • 1
    The search terms you're looking for are [double dispatch](https://en.wikipedia.org/wiki/Double_dispatch) and [multimethods](https://en.wikipedia.org/wiki/Multiple_dispatch). – Oktalist Aug 17 '14 at 21:00
  • 1
    possible duplicate of ["type-switch" construct in C++11](http://stackoverflow.com/questions/22822836/type-switch-construct-in-c11) – Deduplicator Aug 17 '14 at 21:06
  • All good answers. Double dispatch is exactly what I was looking for. Thanks! – Christopher Johnson Aug 17 '14 at 21:20

0 Answers0