김선달
김선달

Reputation: 1562

brace-or-equal-initializers initialization order

If using brace-or-equal-initializers, what's the initializing order of member variables? Are they initialize the same as code order?

struct foo {
    int x = 1;
    int y = x + 1;
} bar;

Will bar.y always be 2 regardless of the compiler?

Upvotes: 3

Views: 453

Answers (2)

TonySalimi
TonySalimi

Reputation: 8437

From Scott Meyers book, Effective C++, item 4:

One aspect of C++ that isn’t fickle is the order in which an object’s data is initialized. This order is always the same: base classes are initialized before derived classes (see also Item 12), and within a class, data members are initialized in the order in which they are declared.

Upvotes: 0

songyuanyao
songyuanyao

Reputation: 173024

Yes, y is guaranteed to be initialized after x. Non-static data members are always initialized in order of their declaration in the class definition, regardless of how they're initialized (by member initializer list or default member initializer, even default initialization).

3) Then, non-static data member are initialized in order of declaration in the class definition.

Upvotes: 3

Related Questions