C++ Multiple Inheritance - why you no work?

前端 未结 2 791
面向向阳花
面向向阳花 2021-01-12 03:53

I am trying to figure out an interesting multiple inheritance issue.

The grandparent is an interface class with multiple methods:

class A
{
public:
          


        
相关标签:
2条回答
  • 2021-01-12 04:30

    You don't have diamond inheritance. The B and C base classes of D each have their own A base class subobject because they do not inherit virtually from A.

    So, in D, there are really four pure virtual member functions that need to be implemented: the A::foo and A::bar from B and the A::foo and A::bar from C.

    You probably want to use virtual inheritance. The class declarations and base class lists would look like so:

    class A
    class B : public virtual A
    class C : public virtual A
    class D : public B, public C
    

    If you don't want to use virtual inheritance then you need to override the other two pure virtual functions in D:

    class D : public B, public C
    {
    public:
        using B::foo;
        using C::bar;
    
        int B::bar() { return 0; }
        int C::foo() { return 0; }
    };
    
    0 讨论(0)
  • 2021-01-12 04:50

    You need to make your base classes virtual in order for them to inherit properly. The general rule is that all non-private member functions and base classes should be virtual UNLESS you know what you're doing and want to disable normal inheritance for that member/base.

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