Order of execution in initializer list in C++
Last Updated :
03 Nov, 2020
Prerequisite: Classes, Constructors, Initializer list
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.
Program 1:
C++
#include <iostream>
using namespace std;
class MyClass {
private :
int b;
int a;
public :
MyClass( int value)
: b(value), a(b * 2)
{
cout << b << " " << a;
}
};
int main()
{
MyClass obj(10);
return 0;
}
|
Program 2:
C++
#include <iostream>
using namespace std;
class MyClass {
private :
int a;
int b;
public :
MyClass( int value)
: b(value), a(b * 2)
{
cout << b << " " << a;
}
};
int main()
{
MyClass obj(10);
return 0;
}
|
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...