Search code examples
c++initializationc++17copy-constructordefault-constructor

Why how and why this implicit conversion works


I don't understand why c1 = {1, 2, 3, 4} and c2 = {5, 6, 7, 8} works fine, there are no declared constructors, and compiler-generated compilers doesn't fit.

I tried to understand by making conversion explicit: (C&) { 1, 2, 3, 4} and (const C&) { 1, 2, 3, 4}, but it doesn't work. If compiler provides default constructor with initializer list, or I'm taking the problem from the wrong side?

#include <cstdlib>
#include <iostream>
using namespace std;

namespace A001 {
class A { public: int a; double b; };
class B { public: int a; double b; };
class C { public: A a; B b; };
void test() {
    C c1 = { 1,2,3,4 }, c2 = { 5,6,7,8 };
        cout << c1.b.a + c2.a.b;
   }
}

Solution

  • This is not an implicit conversion, it's aggregate initialization + brace elision. E.g.

    C c1 = { 1,2,3,4 }
    

    is equivalent to

    C c1{ {1,2}, {3,4} }