C 11 Aggregate Initialization for Classes with Member Initializers
C 11 introduces aggregate initialization using curly braces for classes, allowing initializers to be specified for all non-static data members. However, the standard in C 11 raises the question: Can in-class member initializers exist within aggregate structures?
In C 11, having member initializers in a class makes the structure or class non-aggregate. This restriction stemmed from the belief that in-class member initializers share similarities with user-defined constructors. However, adding member initializers should not automatically disqualify a class from being an aggregate.
The C 14 standard addresses this issue, modifying the definition of aggregate classes to exclude only user-provided constructors, private or protected non-static data members, base classes, and virtual functions. The inclusion of member initializers as a disqualifier has been removed.
Therefore, in C 14, a class like the following is now considered an aggregate:
struct A { int a = 3; int b = 3; }; A a{0, 1};
In C 11, the above code would have been invalid because A is not an aggregate. However, in C 14, the code is valid, and the object a will be initialized with a = 0 and b = 1.
Recent versions of g (5.0 and above) now support C 14's definition of aggregates with non-static member initializers. Therefore, the example code will compile in g with either -std=c 14 or -std=c 1y.
The above is the detailed content of Can Classes with Member Initializers be Aggregates in C 14?. For more information, please follow other related articles on the PHP Chinese website!