Is it legal to initialize a struct with only one array as member using a initializer list directly?

132 views Asked by At
#include <iostream>

class vec
{
public:
    int  arr[2];
};


int main()
{
    vec a = { { 1,2 } };// works 
    vec b = { 1,2 };// works too ,but why ?
    std::cin.get();
}

vec has no constructor other than the default constructor .

But this piece of code compiles ,I wonder why .

http://ideone.com/uyx98o

1

There are 1 answers

0
alain On BEST ANSWER

Aggregate initialization is amazing, you don't even have to get the nesting right to make it work, and you can also provide less values than there are members:

#include <iostream>
#include <string>

struct A {
    struct { int a; std::string b[3]; } a;
    double b, c;
};

int main() {
    A a = { 10, "a", "b", "c", 3.1415 };
    std::cout << a.a.a << " " << a.a.b[0] << " " << a.a.b[2]
              << " " << a.b << " " << a.c;
}

Live