On 27.01.16 21.16, Christopher Pisz wrote:
> Premise: Multiple inheritance is universally accepted as bad
Wrong.
There are problems that are really hard to solve without multiple
inheritance. At least it breaks the "don't repeat yourself" rule.
Example:
Think of an entity data model. Each entity has a immutable, inherently
thread-safe representation and a mutable representation. Of course, any
code that works with the read only (maybe cached) entities is supposed
to work also with local mutable instances rather than the shared
immutable ones. It is up to the caching framework to deliver either
type. But you can always enforce a mutable copy, if you intend to make
changes.
It is straight forward to solve this by inheritance. The mutable classes
inherit from the immutable ones add some further methods.
Additionally there are strong entities (with a strong key), weak
entities (i.e. children of strong entities with sub keys) and simple
entities without any key. This is also straight forward to be serviced
with inheritance. Whatever you can do with a simple entity can be done
with weak or strong entities as well.
Now you have multiple inheritance.
A strong mutable entity inherits from the simple entity as well as from
the strong immutable entity. You need both implicit conversions to make
all code work.
I had to implement something like that in C# and it really wasn't fun
because of the lack of multiple inheritance.
Another example:
Think of a logger API. You may have a FileLogger class and e.g. a
DailyFileLogger class that inherits from the first and added
functionality for logfile rotation.
For performance reasons there are multi-tasking safe implementations
that synchronize write access to the file (even over the network) and
single task implementations that simply keep the file open in exclusive
write mode. Any application that can deal with the local implementation
is supposed to work with the synchronized classes as well.
Again you have multiple inheritance.
> Conclusion: Although the compiler allows you to, you should never use
> multiple inheritance in C++
Well, if you do not know what you are doing then you should avoid
multiple inheritance. Otherwise it might be very useful in some cases.
Of course, like any other pattern one should not abuse it.
It is like multiple dispatch. If you really need it, code becomes really
ugly if the language (like C++) does not support it.
Marcel