Stop reimplementing the virtual table and start using double dispatch

Okay, you’ve ended up in a situation where you’re either

  1. using dynamic_cast* to find out the actual type of a pointer, then moving on to do what you really want, or
  2. checking some enum in a base class to see which derived class it really is so that you can perform type-specific operations on it

* or some other form of run-time type information

You know something is wrong with this, but you can’t think of a satisfactory solution. You’ve already considered adding another virtual function on the base class, but you’re worried about how many virtual functions are already there, or the impact that this might have on consumers of the base class.

Good on you for recognizing that. Admitting you have a problem is the first step to solving it 🙂

In this tutorial, I’ll talk about one solution to this problem I’ve had some success with: the double-dispatch Visitor pattern. With it, you can trim down those long if-else if blocks, separate responsibility into manageable pieces, and even stabilize your interface better.

Continue reading “Stop reimplementing the virtual table and start using double dispatch”