1

I'm new to C++11 and I was wondering how this code works internally:

class MyClass { public: MyClass(int a, double b) { cout << "ctor()" << endl; } }; int main() { MyClass i1{4, 7}; return 0; } 

My understanding of the new initializer list is that it is a class std::initializer_list constructed by special syntax { .... } in the code. So how does this class instance created by {4, 7} internally get transformed to a form that fits the constructor to MyClass? Thanks.

4
  • The syntax {....} can construct a std::initializer_list... or it can do other things. Commented Jun 30, 2016 at 5:33
  • @immibis Is there a good reference on this I can read? Commented Jun 30, 2016 at 5:37
  • 1
    Maybe refer to Item 6 of "Effective Modern C++" Commented Jun 30, 2016 at 5:58
  • @hovo Here you can find the details about initializers. Commented Jun 30, 2016 at 5:59

1 Answer 1

1

I think this is how it happens. Extracted from: Explanation of list initialization at cppreference.com

If the previous stage does not produce a match, all constructors of T participate in overload resolution against the set of arguments that consists of the elements of the braced-init-list, with the restriction that only non-narrowing conversions are allowed. If this stage produces an explicit constructor as the best match for a copy-list-initialization, compilation fails (note, in simple copy-initialization, explicit constructors are not considered at all)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.