Why does virtual inheritance need to be specified in the middle of a diamond hierarchy?

前端 未结 5 2325
醉梦人生
醉梦人生 2021-02-20 06:24

I have diamond hierarchy of classes:

    A
  /   \\
 B     C
  \\   /
    D

To avoid two copies of A in D, we need to use virtual inheritance a

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-20 06:51

    As A is the multiply-inherited class it is those that derive from it directly that have to do so virtual.

    If you have a situation where B and C both derive from A and you want both in D and you can't use the diamond, then D can derive from just one of B and C, and have an instance of the other, through which it can forward functions.

    workaround something like this:

    class B : public A; // not your class, cannot change
    class C : public A; // not your class, cannot change
    
    class D : public B; // your class, implement the functions of B
    class D2 : public C; // your class implement the functions of C
    
    class D
    {
       D2 d2;
    };
    

提交回复
热议问题