2

The C++ standard states that:

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

Why? Wouldn't it be more intuitive if members were initialized in the order they appear in the initializers and then default to order of declaration if they are not listed in the initializers?

EDIT RE: DUPLICATE

The accepted answer in the other question doesn't seem complete (I'm happy to be proved wrong but I need more explanation than there is in that answer).

It states that the reason why initialization is always in order of declaration is that while there may be multiple constructors, there can only be one destructor and it needs to use declaration to determine order of destruction.

I get why the compiler needs to use declaration order for destruction, but I don't understand why it needs to strictly enforce that same ordering at construction. And if they do need to be symmetrical why allow programmers to arbitrarily define the ordering of the initializers. Seems like if members MUST be initialized in a particular order it should be a compiler error to write initializers in a different order.

Mattia
  • 2,251
  • 1
  • 22
  • 27
  • When I write a class definition, I think of it as a blueprint for the class. When I write a constructor, I don't think of it as a blueprint. That could be their logic as well. – druckermanly Jan 10 '15 at 03:02
  • Although a perfectly reasonable question, it is a dupe, see @Borgleader's comment, voted to close it – vsoftco Jan 10 '15 at 03:18

1 Answers1

3

There is excellent explanation at the accepted answer to another SO question

The reason for this ordering is because there is only one destructor, and it has to pick a "reverse order" to destroy the class member. In this case, the simplest solution was to use the order of declaration within the class to make sure that attributes were always destroyed in the correct reverse order.

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Thanks for the link but it doesn't answer the question for me. I get why the compiler needs to use declaration order for destruction, I don't understand why it needs to strictly enforce that same ordering at construction. And if they do need to be symmetrical why allow programmers to arbitrarily define the ordering of the initializers. Seems like if members **MUST** be initialized in a particular order it should be a compiler error to write initializers in a different order. – Mattia Jan 10 '15 at 11:28