A use for multiple inheritance?

Most uses of full scale Multiple inheritance are for mixins. As an example:

class DraggableWindow : Window, Draggable { }
class SkinnableWindow : Window, Skinnable { }
class DraggableSkinnableWindow : Window, Draggable, Skinnable { }

etc…

In most cases, it’s best to use multiple inheritance to do strictly interface inheritance.

class DraggableWindow : Window, IDraggable { }

Then you implement the IDraggable interface in your DraggableWindow class. It’s WAY too hard to write good mixin classes.

The benefit of the MI approach (even if you are only using Interface MI) is that you can then treat all kinds of different Windows as Window objects, but have the flexibility to create things that would not be possible (or more difficult) with single inheritance.

For example, in many class frameworks you see something like this:

class Control { }
class Window : Control { }
class Textbox : Control { }

Now, suppose you wanted a Textbox with Window characteristics? Like being dragable, having a titlebar, etc… You could do something like this:

class WindowedTextbox : Control, IWindow, ITexbox { }

In the single inheritance model, you can’t easily inherit from both Window and Textbox without having some problems with duplicate Control objects and other kinds of problems. You can also treat a WindowedTextbox as a Window, a Textbox, or a Control.

Also, to address your .anotherClass() idiom, .anotherClass() returns a different object, while multiple inheritance allows the same object to be used for different purposes.

Leave a Comment