Open In App

Order of execution in initializer list in C++

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++ program to illustrate the
// order of initializer in list
#include <iostream>
using namespace std;
  
class MyClass {
private:
    // Declared first
    int b;
  
    // Declared Second
    int a;
  
public:
    MyClass(int value)
        : b(value), a(b * 2)
    {
        cout << b << " " << a;
    }
};
  
// Driver Code
int main()
{
    // Create an object
    MyClass obj(10);
  
    return 0;
}

Output:
10 20

Program 2:




// C++ program to illustrate the
// order of initializer in list
#include <iostream>
using namespace std;
  
class MyClass {
private:
    // Declared first
    int a;
  
    // Declared Second
    int b;
  
public:
    MyClass(int value)
        : b(value), a(b * 2)
    {
        cout << b << " " << a;
    }
};
  
int main()
{
  
    // Create an object
    MyClass obj(10);
  
    return 0;
}

Output:
10 65528

Both the outputs are different because the execution takes place according to the order of declaration:


Article Tags :