Is this behavior well-defined?
class Foo
{
int A, B;
public:
Foo(int Bar): B(Bar), A(B + 123)
{
}
};
int main()
{
Foo MyFoo(0);
return 0;
}
Is this behavior well-defined?
class Foo
{
int A, B;
public:
Foo(int Bar): B(Bar), A(B + 123)
{
}
};
int main()
{
Foo MyFoo(0);
return 0;
}
Initialization is done in the order of appearance in the declaration, not the order you write it in the constructor.
Look at this question, it's somewhat similar: Initializer list *argument* evaluation order
No, it's undefined.
A
will be initialized first (it's first in the class definition), and it uses uninitializedB
.Class members are initialized in the order they appear in the class definition, irrespective of their order in the initialization list. Indeed, it is bad practice to mismatch the member definition order with the initialization list order.
If your instance of
Foo
happened to have static duration, like inFoo f(0); int main(){}
, the behavior is well-defined. Objects with static duration are zero-initialized before any other initialization takes place; in that case,A
andB
will be 0 when the constructor is run. After that, though, the behavior is the same: firstA
thenB
, givingA
a value of 123 andB
a value ofBar
(still ugly).No, initialization order is defined by the declaration order in the class itself.
From the C++ standard
12.6.2 [class.base.init] p5
: