Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ member array initalisation without default constructors

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?

like image 397
dronus Avatar asked Apr 20 '15 09:04

dronus


People also ask

Does default constructor initialize members?

Default constructors are one of the special member functions. If no constructors are declared in a class, the compiler provides an implicit inline default constructor. If you rely on an implicit default constructor, be sure to initialize members in the class definition, as shown in the previous example.

Can a class have no default constructor?

Not having a default constructor is no problem, as long as you don't use one. Always specifying an argument at construction is ok, when there is no obvious default argument.

Are arrays automatically initialized to 0 in C++?

An array may be partially initialized, by providing fewer data items than the size of the array. The remaining array elements will be automatically initialized to zero.


1 Answers

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>.

like image 188
TartanLlama Avatar answered Oct 22 '22 07:10

TartanLlama