Implicit List Initialization Constructors for Structs

Viewed 581

GCC 5.4 compiles this without any warnings (using -std=c++11 -Wall -pedantic):

#include <iostream>

struct Coord {
    double x, y;
};

Coord origin() {
    return {0.0, 0.0};
}

int main() {
    Coord c = origin();
    std::cout << "(" << c.x << ", " << c.y << ")\n";
}

It looks like {0.0, 0.0} creates an std::initializer_list that gets used to construct to a Coord, even though I haven't defined such a constructor.

Do structs have implicit conversion constructors for an std::initializer_list? If so, what are the rules for when this constructor is generated and how it works? If not, why does this compile without warning?

1 Answers

“Similarly, we can initialize objects of a class for which we have not defined a constructor using • memberwise initialization, • copy initialization, or • default initialization (without an initializer or with an empty initializer list). For example:

struct Work {
     string author;
     string name;
     int year;
};

Work s9 { "Beethoven",
          "Symphony No. 9 in D minor, Op. 125; Choral",
          1824
      };                         // memberwise initialization

Work currently_playing { s9 };   // copy initialization
Work none {};                    // default initialization”

Excerpt From: Bjarne Stroustrup. “The C++ Programming Language, Fourth Edition.”

Also, here's cppreference: http://en.cppreference.com/w/cpp/language/aggregate_initialization

class type (typically, struct or union), that has no private or protected non-static data members no user-provided, inherited, or explicit (since C++17) constructors (explicitly defaulted or deleted constructors are allowed) (since C++11) no virtual, private, or protected (since C++17) base classes no virtual member functions no default member initializers

Which is an excerpt from an extended description of the above. In human it means if you have a simple class you can initialise it using a list of the appropriate types, laid out in the same way. The cppref page shows how you can even nest the types as long as those criteria hold.

Related