Tuesday, February 16, 2010

Multiple Inheritance - should you?

It is often argued that multiple inheritance in C++ is not a good practice. This is why Java doesn't have this ability. Of course, multiple inheritance in C++ for something that is similar to interface implementation as in Java is reasonable, this is the case when all classes inherited from are pure abstract with no data members and no implementaions, only pure virtual methods, except one base which is the true parent.

However, in some cases you do see in C++ multiple inheritance that is not just interface implementation. And in some cases it seems reasonable. The iostream library is using it quite a lot.

I had a code review in which the developer used multiple inheritance. He said he was considering whether to use it or not and decided it serves his goal. Indeed it was OK, there was a class "SomeSortOfEventHandler" that was of both types "A_CertainEventHandler" and "AnotherKindOfEventHandler", that is, the "SomeSortOfEventHandler" was in fact handler for two kinds of events. In this case there was no need for virtual inheritance from the top parent ("AbstractEventHandler"), as the special "SomeSortOfEventHandler" need to have the data and behavior of both its parents.

So far so good. But at a certain point there was a need to implement a virtual method in two flavors, one for being the child of one parent and the other for being the child of the other. This becomes nasty. One can add to the virtual method a parameter of type T (there is a template class at the top, that differentiate the different families under "AbstractEventHandler") - but this is not so elegant as there is no real need for this parameter. All other alternatives were also breaking the elegancy of the inheritance tree. Conclusion: better to create two separate classes and hold a pointer from one to the other to get the relation between two objects, rather than use multiple inheritance.