1

I was working with a large program with many constructors interacting with each other and I managed to pinpoint the problem to my lack of understand of the order in which the constructors are executed when chaining them together.

When you execute the following:

#include<iostream>
struct one
{
    int x;
    one(int x) {this->x = x; std::cout << x << std::endl;}
};
struct two
{
    int x;
    two(int x) {this->x = x; std::cout << x << std::endl;}
};
struct three
{
    int x;
    three(int x) {this->x = x; std::cout << x << std::endl;}
};

struct parent
{
    one o1;
    two o2;
    three o3;
    parent():o1(1), o2(2), o3(3){}
};

int main()
{
    parent p;
}

you will get the following output:

1
2
3

However when you change the code in parent to:

struct parent
{
    three o3;
    two o2;
    one o1;

    parent():o1(1), o2(2), o3(3){}
};

you get

3
2
1

This seems to suggest that the order in which the constructors are called are determined by the order the member variables/objects are placed in the struct and not the order in which the constructor calls are placed in the "chain" (the parent constructor in this case).

This is unintuitive enough to me that I was wondering whether this behavior is well documented and intended or whether I am simply fiddling with undefined behavior. In other words, would it be bad practice to write code that depends on this property?

Thanks in advance

MathGeek
  • 123
  • 5
  • Composition object are constructed in the order they appear in the object declaration. I do not have a citation handy, so I'll let someone else handle the details. The terminology "parent" is usually used for inheritance. – Kenny Ostrom Jan 04 '20 at 01:01
  • @JosephSible-ReinstateMonica Yes it does. Thanks! – MathGeek Jan 04 '20 at 01:05
  • Fairly well documented. See [Initialization Order here](https://en.cppreference.com/w/cpp/language/initializer_list) – user4581301 Jan 04 '20 at 01:15
  • In case you're curious where this behavior is specified in the standard, [class.base.init/13.3](https://timsong-cpp.github.io/cppwp/n4659/class.base.init#13.3) – WhozCraig Jan 04 '20 at 01:32

0 Answers0