A use for multiple inheritance?

后端 未结 12 1876
暖寄归人
暖寄归人 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 07:55

    I find multiple inheritance particularly useful when using mixin classes.

    As stated in Wikipedia:

    In object-oriented programming languages, a mixin is a class that provides a certain functionality to be inherited by a subclass, but is not meant to stand alone.

    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.

    But they may also inherit from other classes as part of their normal class structure, so it is quite common for these classes to use multiple inheritance in this respect.

    An example of multiple inheritance:

    class Animal
    {
       virtual void KeepCool() const = 0;
    }
    
    class Vertebrate
    {
       virtual void BendSpine() { };
    }
    
    
    class Dog : public Animal, public Vertebrate
    {
       void KeepCool() { Pant(); }
    }
    

    What is most important when doing any form of public inheritance (single or multiple) is to respect the is a relationship. A class should only inherit from one or more classes if it "is" one of those objects. If it simply "contains" one of those objects, aggregation or composition should be used instead.

    The example above is well structured because a dog is an animal, and also a vertebrate.

提交回复
热议问题