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?
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.
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.
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.
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With