A use for multiple inheritance?

后端 未结 12 1875
暖寄归人
暖寄归人 2020-11-29 07:29

Can anyone think of any situation to use multiple inheritance? Every case I can think of can be solved by the method operator

AnotherClass() { return this-&         


        
相关标签:
12条回答
  • 2020-11-29 08:05

    I had to use it today, actually...

    Here was my situation - I had a domain model represented in memory where an A contained zero or more Bs(represented in an array), each B has zero or more Cs, and Cs to Ds. I couldn't change the fact that they were arrays (the source for these arrays were from automatically generated code from the build process). Each instance needed to keep track of which index in the parent array they belonged in. They also needed to keep track of the instance of their parent (too much detail as to why). I wrote something like this (there was more to it, and this is not syntactically correct, it's just an example):

    class Parent
    {
        add(Child c)
        {
            children.add(c);
            c.index = children.Count-1;
            c.parent = this;
        }
        Collection<Child> children
    }
    
    class Child
    {
        Parent p;
        int index;
    }
    

    Then, for the domain types, I did this:

    class A : Parent
    class B : Parent, Child
    class C : Parent, Child
    class D : Child
    

    The actually implementation was in C# with interfaces and generics, and I couldn't do the multiple inheritance like I would have if the language supported it (some copy paste had to be done). So, I thought I'd search SO to see what people think of multiple inheritance, and I got your question ;)

    I couldn't use your solution of the .anotherClass, because of the implementation of add for Parent (references this - and I wanted this to not be some other class).

    It got worse because the generated code had A subclass something else that was neither a parent or a child...more copy paste.

    0 讨论(0)
  • 2020-11-29 08:10

    Most people use multiple-inheritance in the context of applying multiple interfaces to a class. This is the approach Java and C#, among others, enforce.

    C++ allows you to apply multiple base classes fairly freely, in an is-a relationship between types. So, you can treat a derived object like any of its base classes.

    Another use, as LeopardSkinPillBoxHat points out, is in mix-ins. An excellent example of this is the Loki library, from Andrei Alexandrescu's book Modern C++ Design. He uses what he terms policy classes that specify the behavior or the requirements of a given class through inheritance.

    Yet another use is one that simplifies a modular approach that allows API-independence through the use of sister-class delegation in the oft-dreaded diamond hierarchy.

    The uses for MI are many. The potential for abuse is even greater.

    0 讨论(0)
  • 2020-11-29 08:10

    I think it would be most useful for boilerplate code. For example, the IDisposable pattern is exactly the same for all classes in .NET. So why re-type that code over and over again?

    Another example is ICollection. The vast majority of the interface methods are implemented exactly the same. There are only a couple of methods that are actually unique to your class.

    Unfortunately multiple-inheritance is very easy to abuse. People will quickly start doing silly things like LabelPrinter class inherit from their TcpIpConnector class instead of merely contain it.

    0 讨论(0)
  • 2020-11-29 08:11

    I suspect that in C++, MI is best use as part of a framework (the mix-in classes previously discussed). The only thing I know for sure is that every time I've tried to use it in my apps, I've ended up regretting the choice, and often tearing it out and replacing it with generated code.

    MI is one more of those 'use it if you REALLY need it, but make sure you REALLY need it' tools.

    0 讨论(0)
  • 2020-11-29 08:13

    The following example is mostly something I see often in C++: sometimes it may be necessary due to utility classes that you need but because of their design cannot be used through composition (at least not efficiently or without making the code even messier than falling back on mult. inheritance). A good example is you have an abstract base class A and a derived class B, and B also needs to be a kind of serializable class, so it has to derive from, let's say, another abstract class called Serializable. It's possible to avoid MI, but if Serializable only contains a few virtual methods and needs deep access to the private members of B, then it may be worth muddying the inheritance tree just to avoid making friend declarations and giving away access to B's internals to some helper composition class.

    0 讨论(0)
  • 2020-11-29 08:15

    An example of how our product uses mixin classes is for configuration save and restore purposes. There is an abstract mixin class which defines a set of pure virtual methods. Any class which is saveable inherits from the save/restore mixin class which automatically gives them the appropriate save/restore functionality.

    This example doesn't really illustrate the usefulness of multiple inheritance. What being defined here is an INTERFACE. Multiple inheritance allows you to inherit behavior as well. Which is the point of mixins.

    An example; because of a need to preserve backwards compatibility I have to implement my own serialization methods.

    So every object gets a Read and Store method like this.

    Public Sub Store(ByVal File As IBinaryWriter)
    Public Sub Read(ByVal File As IBinaryReader)
    

    I also want to be able to assign and clone object as well. So I would like this on every object.

    Public Sub Assign(ByVal tObject As <Class_Name>)
    Public Function Clone() As <Class_Name>
    

    Now in VB6 I have this code repeated over and over again.

    Public Assign(ByVal tObject As ObjectClass)
        Me.State = tObject.State
    End Sub
    
    Public Function Clone() As ObjectClass
        Dim O As ObjectClass
        Set O = New ObjectClass
        O.State = Me.State
        Set Clone = 0
    End Function
    
    Public Property Get State() As Variant
        StateManager.Clear
        Me.Store StateManager
        State = StateManager.Data
    End Property
    
    Public Property Let State(ByVal RHS As Variant)
        StateManager.Data = RHS
        Me.Read StateManager
    End Property
    

    Note that Statemanager is a stream that read and stores byte arrays.

    This code is repeated dozens of times.

    Now in .NET i am able to get around this by using a combination of generics and inheritance. My object under the .NET version get Assign, Clone, and State when they inherit from MyAppBaseObject. But I don't like the fact that every object inherits from MyAppBaseObject.

    I rather just mix in the the Assign Clone interface AND BEHAVIOR. Better yet mix in separately the Read and Store interface then being able to mix in Assign and Clone. It would be cleaner code in my opinion.

    But the times where I reuse behavior are DWARFED by the time I use Interface. This is because the goal of most object hierarchies are NOT about reusing behavior but precisely defining the relationship between different objects. Which interfaces are designed for. So while it would be nice that C# (or VB.NET) had some ability to do this it isn't a show stopper in my opinion.

    The whole reason that this is even an issue that that C++ fumbled the ball at first when it came to the interface vs inheritance issue. When OOP debuted everybody thought that behavior reuse was the priority. But this proved to be a chimera and only useful for specific circumstances, like making a UI framework.

    Later the idea of mixins (and other related concepts in aspect oriented programming) were developed. Multiple inheritance was found useful in creating mix-ins. But C# was developed just before this was widely recognized. Likely an alternative syntax will be developed to do this.

    0 讨论(0)
提交回复
热议问题