tags:

views:

433

answers:

2

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_;
};
+10  A: 

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.

AraK
I just discovered this by pure accident.
Matt H
In fact, good compilers will warn if you have a different order in the declaration versus the constructor initialiser list. For example, see `-Wreorder` in gcc.
Greg Hewgill
The reason for which they are constructed in the member declaration order and not in the order in the constructor is that one may have several constructors, but there is only one destructor. And the destructor destroy the members in the reserse order of construction.
AProgrammer
@AProgrammer, great. I never thought of it :)
AraK
Great explanation @AProgrammer, thanks for that.
Matt H
+15  A: 

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).

...

GMan
+1 for the quote.
AraK