Ugly Inheritance Problem

Today I fought a nasty C++ inheritance problem. It's not that I wasn't expecting some problems, I just didn't expect the kind of problems I ran into. The design is a pretty standard one for the finance industry for tradable instruments:

Original Design

There are clearly two diamond problems in this model: the first is ending on the Future and going back to the Instrument, and the second is ending on the Stock and going back to the Underlying and Instrument.

Interestingly enough, I was able to make the blue inheritances virtual and it all compiled. But when I tried to run it, I got constructor problems in the Instrument class that I should not have gotten. Clearly, there was something more going on here, and I had to be more explicit.

Alternatively, I could look at the design and realize a few facts:

  • The only Futurable Instrument is a Stock - seems odd, but with this model, that's all that can have futures on it. We can certainly throw indexes and other instruments in the "stock" class, or even further subclass it, but it's a nice simplification.
  • All Underlyings are Optionable - again, because of the way the design is laid out, it's clear that the Optionable feature can be incorporated into the Underlying without limiting the model.

The only problem with these two simplifications is that I can't have something that is Futurable and not Optionable. As I think about what I've done in the past, I think this is a fairly good bet.

With this, the design becomes much simpler:

Revised Design

This has only the one diamond problem, and it's easily solved with the virtual inheritances shown in blue. It's also a lot simpler to see and understand, and there are no "placeholder classes" that simply have to be there for classification purposes. I'm not sure I like this a lot more, but it's cleaner and it'll work better, and has fewer moving parts, so on the whole, I like it more.