Re: About multiple inheritance again
* Alex:
struct A {int x; A(int X = 0):x(X) {}};
struct B: virtual A {B():A(1) {}};
struct C: virtual A {C():A(2) {}};
struct D: B, C {};
cout << A().x << endl; // <--- prints 0
cout << B().x << endl; // <--- prints 1
cout << C().x << endl; // <--- prints 2
cout << D().x << endl; // <--- prints 0 (why!?)
Because class D specifies (implicitly) default construction of the A
sub-object.
Construction of a virtual base class sub-object is always specified by
the most derived class: if you don't do it explicitly, then you're
specifying default construction.
Try
struct D: B, C, A(3) {}
or simply try to remove the default for A's argument.
The fragment above was compiled and linked by MINGW32 on PC and
SunSoft 5.3 on Solaris. Results are the same.
Can anybody please explain what constructors are called in last line
and in what order?
That depends on what you mean by "called". ;-)
Constructor bodies are executed in the order A, B, C, D, and we say that
the sub-objects are /initialized/ in this order, because initialization
isn't complete until the constructor body has executed successfully.
However, that doesn't correspond so much to "calls" as to "call
returns". The order of constructor call returns is A, B, C, D.
Constructor's initializer lists are evaluated in the order D, A, B, C.
You have a source code call of D(). Its initializer list specifies
implicitly a call of A(), called, finished, proceeding with the calls of
B(), then C(), finished, proceeding with execution of body of D().
Hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]