In this article we will discuss how to use std::initializer_list<T> to initialize member variables.

Suppose we have a class Point that has 3 member variables representing x, y & Z axis coordinates. It has a parameterized constructor too i.e.

We can create a object of Point by passing std::initializer_list<int> i.e. {1,2,3} as argument i.e.

 

Compiler will automatically create a std::initializer_list<int> object refereing to {1,2,3} & the search for a constructor that accepts a std::initializer_list<int> as an argument, if not then any constructor that accepts 3 ints.

Checkout complete example as follows,

Output:

But what if we have an another constructor that accepts a std::initializer_list<int> as an argument i.e.

In this case when we will create a Point object with {1,2,3} it will always give preference to constructor with std::initializer_list<int> i.e.

 

So, to call the other constructor we need to call the constructor using original way i.e.

Complete example is as follows,

Output

Passing variable arguments with std::initialer_list<T>

We can also pass variable arguments to a constructor or any other function that accepts std::initializer_list<T> as an argument i.e.

Output: