Possible Duplicate:
Member fields, order of construction
If i have a class with two members like this:
class A
{
int a;
int b;
A() {}
};
Is the order in which a
and b
are constructed undefined?
If I use cl
, then no matter in which order I call the constructors, the members are always constructed in the order in which they are declared in the class. In this case it would always be a
then b
, even if I define the constructor for A
like:
A() : b(), a() {}
But I am assuming that that is just the behaviour of the specific compiler.
No. Members are constructed in the order in which they are declared.
You are advised to arrange your initializer list in the same order, but you are not required to do so. It's just very confusing if you don't and may lead to hard-to-detect errors.
Example:
struct Foo {
int a; int b;
Foo() : b(4), a(b) { } // does not do what you think!
};
This construction is actually undefined behaviour, because you're reading an uninitialized variable in the initializer a(b)
.
Standard reference (C++11, 12.6.2/10):
— 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