TITLE: virtual inheritance and non-default constructors (Source: comp.std.c++, 12 Sep 2000) PYTTE: Anders Pytte > > The reason is because of virtual inheritance, the final class X must > > construct the base class A, and since you leave A out of the initializer > > list, the default constructor is called. I don't see any way to take > > this into account in your design, other than by making the inheritance > > non-virtual. REICO: Reico GmbH > Can anyone explain this rule? Due to this rule (and only this) virtual > inheritance is quite useless for me in practice. I could imagine the > following rule: > You MAY explicitly state a c'tor for a virtual base class from every > derived class. If you don't, the first virtual base class c'tor reached > during construction is taken. CLAMAGE: Steve Clamage The C++ object model requires the object's type to be determined by the constructor that is running, and when a constructor runs, all of its base classes are fully constructed. Other object models are possible, but this model ensures that anything that happens automatically is safe, and that you can't accidently access unconstructed objects or sub-objects. (Similar considerations apply to destruction.) That object model requires that virtual base classes be constructed first, because any intermediate base class could wind up referring directly or indirectly to a virtual base class during construction. Now consider object layout, where no class is empty. class VB { ... }; class A : public virtual VB { ... }; class B : public virtual VB { ... }; class C : public A, public B { ... }; The location of VB relative to the start of a complete class A or B object cannot be the same as its location relative to the start of it as a subobject of a C. (Although relative locations might be the same for an A or a B, it cannot be the same for both cases.) Since adjustment of pointers between virtual base and derived classes (such as when calling virtual functions) depends on the subobject offsets, the vtable data for a VB in A or B is different depending on whether the A or B is the complete object or a subobject. The correct offset information is available only for the most-derived object, which is why the most-derived constructor must intialize the virtual base classes. _______________________________________________ cpptips mailing list http://cpptips.hyperformix.com