Jess <> wrote:
> When I define default constructors, I tend to use constructor
> initializers for member data. However, I was told the order in which
> members are initialized is determined by the order of declaration in
> the class, instead of the order they appear in the constructor
> initializer. This would introduce interdependencies. Therefore, it
> is safer to avoid such interdependence by assigning values to these
> members inside the constructor body rather than initializing them in
> the intializer. Could someone explain to me why this is the case?
> Moreover, what kind of error could possibly happen due to the
> "interdependency"?
Here is a contrived example, but it demonstrates the point:
#include <iostream>
struct Foo {
const int c;
int i;
Foo(int x) : c(x), i(2 * c) { }
};
struct Bar {
int i;
const int c;
Bar(int x) : c(x), i(2 * c) { }
};
int main()
{
using std::cout;
Foo f(3);
cout << f.c << ", " << f.i << '\n';
Bar b(3);
cout << b.c << ", " << b.i << '\n';
}
Output:
3, 6
3, 8529120
In Foo, first the const int c is initialized with the value of 3, then
the int i is initialized with the value of (2*3).
In Bar, since i was declared before c, then i's initialization occurs
first. At this point the value of c is garbage (and thus reading it is
really undefined behavior), so i is initialized with 2*garbage before c
is initialized.
--
Marcus Kwok
Replace 'invalid' with 'net' to reply
|