Search⌘ K
AI Features

Discussion: An Overloaded Container

Learn how C++ chooses between overloaded constructors when using different initialization styles. Understand the difference between braced-init-lists and std::initializer_list, and how overload resolution prioritizes constructors, clarifying behaviors in container initialization.

Run the code

Now, it’s time to execute the code and observe the output.

C++ 17
#include <initializer_list>
#include <iostream>
struct Container
{
Container(int, int)
{
std::cout << "Two ints\n";
}
Container(std::initializer_list<float>)
{
std::cout << "std::initializer_list<float>\n";
}
};
int main()
{
Container container1(1, 2);
Container container2{1, 2};
}

Understanding the output

The Container struct has two constructors, one taking two int types and one taking std::initializer_list<float>. Two objects of type Container are constructed, both with two int types as arguments. But the one difference is that one object is constructed using parentheses—(1,2)—and the other using curly braces—{1,2}. Which constructor is called in each case? ...