When a "Private" Constructor in C Goes Public
In C , declaring a type's default constructor as private typically restricts its accessibility. However, in certain scenarios, this restriction may be unexpectedly bypassed.
Consider the following example:
class C { C() = default; // Private default constructor }; int main() { C c; // Error: Constructor is private auto c2 = C(); // Error: Constructor is private }
In this case, both attempts to create instances of C fail due to the private constructor. Surprisingly, this restriction appears to be lifted when using curly braces to initialize C directly:
class C { C() = default; }; int main() { C c{}; // Success: Curly braces allow object initialization auto c2 = C{}; // Success: Initialization not affected by private constructor }
Unveiling the Trick
This peculiar behavior stems from C 14's aggregate initialization rules. As per 8.4.2/5 of [dcl.fct.def.default], a default constructor is not considered "user-provided" if it was explicitly defaulted in its first declaration. Since C's default constructor fits this criteria, it's not treated as user-provided.
Consequently, C meets the definition of an aggregate as per 8.5.1/1 of [dcl.init.aggr]: it has no user-provided constructors, private or protected non-static data members, base classes, or virtual functions.
Aggregate Initialization
An aggregate is a special type with simplified initialization rules. Curly braces in this context signify aggregate initialization, which allows the creation of an object even with private constructors. In our case, the compiler treats {} as an initializer list, bypassing the private constructor restriction and initializing C as an aggregate.
The above is the detailed content of Why Does Using Curly Braces Allow Initialization of a Class with a Private Default Constructor in C ?. For more information, please follow other related articles on the PHP Chinese website!