order of execution in case of multiple inheritance
c++, multiple-inheritance
Solution
The virtual base class constructors are always executed first according to the C++ standard. From the working draft N3242, page 272 line 10, we learn that:
- Virtual base class constructors go first, in the order of a left-to-right depth-first traversal of the inheritance graph.
- Direct base classes go next, in declaration order.
So the behavior you see is exactly what is required in the C++ standard. It makes sense, because the virtual base classes may show up multiple times in the inheritance and of course they can each only be constructed once. Hence there has to be an initial round of virtual base class construction, followed by the usual non-virtual base class construction.
There is also a nice explanation on this page.
Problem
``` class A: public B, public C { }; ``` In this case order of execution is: ``` B(); // base(first) C(); // base(second) A(); // derived ``` ``` class A: public B, virtual public C { }; ``` But in this case,when i write virtual with class c while inheriting,order of ``` // execution becomes: C(); // virtual base B(); // ordinary base A(); // derived ``` i have read somewhere that order of calling constructor depends on the order of declaration while inheriting multiple classes but how does the order of execution gets changed on writing virtual with a class.I am not able to get why i am getting such result.