C++ member array initalisation without default constructors
Asked Answered
P

1

13

I have a class Thing sporting no default constructor.

Now we define another class, which now has to initalise the array elements at once, as without a default constructor, no late assignment can be made. So we have:

class TwoThings
{
    public:

    Thing things[2];

    TwoThings() : things({Thing("thing 1"),Thing("thing 2")})
    {
    }
}

Is this the correct way?

GCC compiles it fine, while Clang does not, stating an "initializer list" should be used. I tried several alternative ways like double braces {{ ... }} and such, but can't manage to get a compiling equivalent for Clang.

How to initialise arrays without default constructor in Clang?

Pairs answered 20/4, 2015 at 9:16 Comment(0)
I
14

Yes, parenthesised member array initialization is a GCC extension. To make it standard, you can just use a single set of braces (requires C++11):

TwoThings() : things{Thing("thing 1"),Thing("thing 2")}
{
}

If you can't use C++11, you might want to use a different storage method, like std::pair<Thing,Thing> or std::vector<Thing>.

Illuminating answered 20/4, 2015 at 9:22 Comment(4)
So there is no way without these extension or C++11 (breaks many of my older libraries) to initialize an array?Pairs
You could use a different storage method, like std::pair<Thing,Thing> or std::vector<Thing>.Illuminating
I guess std::vector would need elements having the default constructor too?Pairs
No, you can use reserve and push_back instead of using resize to stop it from default constructing anything.Illuminating

© 2022 - 2024 — McMap. All rights reserved.