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