Can someone point me please, to a corresponding paragraph of the C++ standard, or maybe can provide some explanation why my code does not compile if I uncomment the text ({123})
?
Generally speaking I understand what something wrong with usage of default member initialization and initialization via initializer list, but I can't refer to exact reasons.
enum class MY: int
{
A = 1
};
struct abc
{
int a;/*{123};*/ //compilation failed if uncommented
MY m;
};
abc a = {1, MY::A};
Compiler error, in case of uncommented text:
error: could not convert ‘{1, A}’ from ‘<brace-enclosed initializer list>’ to ‘abc’
The below syntax:
abc a = {1, MY::A};
is a list-initialization which may perform differently depending on the type being initialized. Without the non-static data member initializer (/*{123};*/
), your struct is an aggregate and the case falls under [dcl.init.list]/p3:
- Otherwise, if
T
is an aggregate, aggregate initialization is performed.
However, to be an aggregate type, the following conditions must be met in C++11:
An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal-initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).
That is, the usage of NSDMI (non-static data member initialization) breaks the above set of rules, and as a result, an instance of this type can no longer be list-initialized.
This rule has changed in C++14, and the current wording reads [dcl.init.aggr]/p1:
An aggregate is an array or a class with
(1.1) no user-provided, explicit, or inherited constructors ([class.ctor]),
(1.2) no private or protected non-static data members ([class.access]),
(1.3) no virtual functions, and
(1.4) no virtual, private, or protected base classes ([class.mi]).
[ Note: Aggregate initialization does not allow accessing protected and private base class' members or constructors. — end note ]
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