Open In App

How to Use Initializer Lists in Constructors in C++?

In C++, the initializer list in constructors can be used to initialize member variables with a list of values. In this article, we will learn how to use initializer lists in the constructor in C++.

Initializer List in Constructor in C++

We can use initializer_lists in constructors for initializing the members of the class with a list of values.



Syntax to Declare Initializer List

initializer_list<type> name;

We can declare the argument of the constructor as an initializer_list object and then pass the desired number of arguments at the time of construction.

C++ Program to Use Initializer Lists in Constructors

The below example demonstrates how we can use the initializer list in the constructor in C++.






// C++ program to show how to use initializer list in
// constructor
#include <initializer_list>
#include <iostream>
#include <vector>
using namespace std;
  
// class declartion
class MyClass {
private:
    vector<int> vec;
  
public:
    MyClass(initializer_list<int> initList)
        : vec(initList){}
  
    void display()
    {
        for (const auto& val : vec) {
            cout << val << " ";
        }
        cout << endl;
    }
};
  
// driver code
int main()
{
    // passing initializer list
    MyClass obj({ 1, 2, 3, 4, 5 });
  
    obj.display();
    return 0;
}

Output
1 2 3 4 5 

Time Complexity: O(N), here N is the number of elements in the vec vector.
Auxilliary Space: O(N)

Explanation: In the above code, MyClass has a constructor that takes an std::initializer_list<int> that allows us to initialize MyClass with a list of integers, which are stored in a std::vector<int>

Article Tags :