Search code examples
c++c++11initializer-liststdarray

Initialize std::array of classes in a class constructor


I'm trying to initialize a std::array of objects within the constructor of another class. It seems like aggregate initialization should work here, but I can't figure out the appropriate syntax. How do I go about doing this?

class A {
        const int a;
public:
        A(int an_int) : a(an_int) {}
};

class B {
        std::array<A,3> stuff;
public:
        B() :
        stuff({1,2,3}) // << How do I do this?
        {}
};

int main() {
        B b;
        return 0;
}

Solution

  • You just need an extra pair of braces:

    B() : stuff({{1,2,3}}) {}
                ^       ^
    

    Or you can replace parentheses with braces:

    B() : stuff {{1,2,3}} {}
                ^       ^