Multiple inheritance and pure virtual functions

后端 未结 3 1113
Happy的楠姐
Happy的楠姐 2021-01-04 02:13

The following code:

struct interface_base
{
    virtual void foo() = 0;
};

struct interface : public interface_base
{
    virtual void bar() = 0;
};

struct         


        
3条回答
  •  太阳男子
    2021-01-04 02:49

    You have two interface_base base classes in your inheritance tree. This means you must provide two implementations of foo(). And calling either of them will be really awkward, requiring multiple casts to disambiguate. This usually is not what you want.

    To resolve this, use virtual inheritance:

    struct interface_base
    {
        virtual void foo() = 0;
    };
    
    struct interface : virtual public interface_base
    {
        virtual void bar() = 0;
    };
    
    struct implementation_base : virtual public interface_base
    {
        void foo();
    };
    
    struct implementation : public implementation_base, virtual public interface
    {   
        void bar();
    };
    
    int main()
    {
        implementation x;
    }
    

    With virtual inheritance, only one instance of the base class in question is created in the inheritance heirarchy for all virtual mentions. Thus, there's only one foo(), which can be satisfied by implementation_base::foo().

    For more information, see this prior question - the answers provide some nice diagrams to make this all more clear.

提交回复
热议问题