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

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

    I'm not sure of the exact reason they chose to design virtual inheritance this way, but I believe the reason has to do with object layout.

    Suppose that C++ was designed in a way where to resolve the diamond problem, you would virtually inherit B and C in D rather than virtually inheriting A in B and C. Now, what would the object layout for B and C be? Well, if no one ever tries to virtually inherit from them, then they'd each have their own copy of A and could use the standard, optimized layout where B and C each have an A at their base. However, if someone does virtually inherit from either B or C, then the object layout would have to be different because the two would have to share their copy of A.

    The problem with this is that when the compiler first sees B and C, it can't know if anyone is going to be inheriting from them. Consequently, the compiler would have to fall back on the slower version of inheritance used in virtual inheritance rather than the more optimized version of inheritance that is turned on by default. This violates the C++ principle of "don't pay what you don't use for," (the zero-overhead principle) where you only pay for language features you explicitly use.

提交回复
热议问题