Constructor initialization-list evaluation order

C++GccC++ Faq

C++ Problem Overview


I have a constructor that takes some arguments. I had assumed that they were constructed in the order listed, but in one case it appears they were being constructed in reverse resulting in an abort. When I reversed the arguments the program stopped aborting. This is an example of the syntax I'm using. The thing is, a_ needs to be initialized before b_ in this case. Can you guarantee the order of construction?

e.g.

class A
{
  public:
    A(OtherClass o, string x, int y) :
      a_(o), b_(a_, x, y) { }

    OtherClass a_;
    AnotherClass b_;
};

C++ Solutions


Solution 1 - C++

It depends on the order of member variable declaration in the class. So a_ will be the first one, then b_ will be the second one in your example.

Solution 2 - C++

To quote the standard, for clarification:

> 12.6.2.5

>Initialization shall proceed in the following order:

> ...

> - Then, nonstatic data members shall be initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

> ...

Solution 3 - C++

The standard reference for this now appears to be 12.6.2 section 13.3:

> (13.3) — 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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhookenzView Question on Stackoverflow
Solution 1 - C++Khaled AlshayaView Answer on Stackoverflow
Solution 2 - C++GManNickGView Answer on Stackoverflow
Solution 3 - C++Adam GetchellView Answer on Stackoverflow