Skip to content
Related Articles

Related Articles

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

10 20

Program 2:



C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


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.

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :