why are virtual base non-default constructors not called unless most-derived base explicitly invokes them?

邮差的信 提交于 2019-12-01 18:45:54

The entire purpose of having virtual inheritance is to solve the diamond problem. Once you have a virtual base class, and your hierarchy looks like this:

  A
 / \
B   C
 \ /
  D

You need to know when to construct the A. You can't have B construct it and then C then immediately overwrite it - you need it to be constructed exactly once. Okay, so when can we do that? The simplest choice is just: make the most derived class do it! So when we're initializing the B subobject of D, it will not initialize its A subobject because B is not the most derived type.

In your case, your hierarchy is still linear:

A
|
B
|
C

but the most derived type, C, has to initialize all the virtual bases - A and B. B won't initialize its A subobject for the same reason as it didn't in the complicated example.

It's unlikely that you'll get any support to change the language. Virtual inheritance is only useful in multiple inheritance scenarios.

Why must B(int a, int b)'s invocation of A(a) be ignored here?

Because the unique A sub-object has already been constructed. A constructor isn't an ordinary function, you can't just call it anywhere.

You can write

C(int a, int b, int c)
    : A(a), B(a, b), _c(c)
    { ... }

which will give the body of B::B(int, int) the parameter that passed to A::A(int)

This behavior is because of virtual base class. Since A is the virtual base class it is constructed by the most derived class.
you can check about diamond shape inheritance problem and this discussion on similar question to understand why it has to be in this way.
First understand how diamod shape problem is solved by virtual base class.
class A { ...}
class B: virtual public A {...}
class C: virtual public A {...}
class D: public B, public C {...}
When you make the base class as virtual there will be one base class object. The intermediate derived class objects will all refer to the same single base class object. I.e. here if an object of D is created then B::A and C::A both will refer the same object. This single object is of base class of both B and C. So there are two derived classes to construct this single object if it allowed the construction of base class object by intermediate classes. This ambiguity is solved by giving the most derived class the responsibility to construct the virtual base class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!