2
votes

I want to know the reason why constructors are called in the order in which objects are declared.

I read this question but i am not getting the reason specified there as a comment.

Stated reason is:

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 reverse order of construction.

Can someone please explain this?

2
How would the compiler know what order the members were initialized in if that order could change depending on which constructor was called? - Galik

2 Answers

7
votes
  1. sub-object destructors should always be called in reverse order compared to sub-object constructors (otherwise way too many things will fall apart)

  2. There can be multiple constructors of the object, each with it's own order of sub-objects in the list

  3. If we call sub-object constructors in the order which is specific to each object constructor, we won't be able to get one single order for sub-object destructors.

  4. Hence, the decision to have in the order of declaration, which doesn't depend on the order of sub-objects in different object constructors.

1
votes

A basic language design principle in C++ is that "you don't pay for what you don't use".

It's not perfectly applied, e.g. one does pay for threads, and for exceptions, even if they're not used. Which is one reason why C still has a good niche. But in general, if a language feature would impose some cost even where it's not used, then it's not there.

Ensuring that destruction order is opposite of construction order is essential for correctness. But doing that for arbitrary construction orders, which might be defined in other translation units, would incur the overhead of a dynamically established destruction order. And that cost would very rarely buy any advantage (e.g., I have never needed different initialization orders for different constructors, and I have used C++ since the 1990's).