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

前端 未结 5 2441
醉梦人生
醉梦人生 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:42

    Question: Why does virtual inheritance needs to be performed at B and C, even though the ambiguity is at D?

    Because B's and C's methods must know they might have to work on objects whose layout is much different from B's and C's own layouts. With single inheritance it is not a problem, because derived classes just append their attributes after parent's original layout.

    With multiple inheritance you cannot to that because there's no single parent's layout in the first place. Moreover (if you want to avoid A's duplication) parents' layouts need to overlap on A's attributes. Multiple inheritance in C++ hides quite a lot of complexity.

提交回复
热议问题