Consider the following code:
class A {};
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {};
D d;
The Visual Studio's compiler first calls the constructor of class B, then the constructor of class C. But is this a Rule, i.e. does the ISO C++ standard guarantee the order of constructor call?
It's guaranteed. From §12.6.2 [class.base.init]/p11 of N3797:
In a non-delegating constructor, initialization proceeds in the following order:
- First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.
- Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
- Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With