Skip to content
Related Articles

Related Articles

Improve Article

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++




// 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++




// 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:

  • 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.
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :