虛基類的子類的子類在多重繼承時,建構函式初始化父類的建構函式將不會將資訊傳給虛基類,但可以顯示調用對應虛基類的建構函式來構造自身對象,從而獲得一個虛基類的對象避免多重繼承的衝突;如果未顯示調用虛基類的建構函式,將自動調用其預設的建構函式。
C++ primer plus 6th
14. Reusing Code in C++
New Constructor Rules
SingingWaiter(const Worker & wk, int p = 0, int v = Singer::other) : Waiter(wk,p), Singer(wk,v) {} // flawed
The problem is that automatic passing of information would pass wk to the Worker object via two separate paths (Waiter and Singer).
To avoid this potential conflict, C++ disables the automatic passing of information through an intermediate class to a base class if the base class is virtual. Thus, the previous constructor will initialize the panache and
voice members, but the information in the wk argument won’t get to the Waiter subobject. However, the compiler must construct a base object component before constructing derived objects;
in this case, it will use the default Worker constructor.
If you want to use something other than the default constructor for a virtual base class,
you need to invoke the appropriate base constructor explicitly. Thus, the constructor should look like this:
SingingWaiter(const Worker & wk, int p = 0, int v = Singer::other) : Worker(wk), Waiter(wk,p), Singer(wk,v) {}