In this article, we will discuss the order of execution in the initializer list in C++. Generally, the order of execution is from top to bottom and left to right. But a rare condition arises where this rule fails is when the initializer list is used in class. In the initializer list, the order of execution takes place according to the order of declaration of member variables. While using the initializer list for a class in C++, the order of declaration of member variables affects the output of the program.
Both the outputs are different because the execution takes place according to the order of declaration:
- In the first program, b is declared first, so b is assigned the value of 10 and then a is declared, later a is assigned b*2. So, the output is 10 20.
- In the second program, a is declared first and then b. So, first, a is assigned b*2, but b is not initialized yet. So, some garbage value is assigned to a. Later b is assigned the value of 10.