Home > Article > Backend Development > Why Does a Private Default Constructor Prevent Object Creation in C But Braced Initialization Works?
When is a Private Constructor Not a Private Constructor?
In C , making a constructor private seems like a straightforward way to prevent object creation outside the class. However, unexpected behavior arises when a default constructor is declared private.
Consider the following code:
class C { C() = default; }; int main() { C c; // Error: Private constructor auto c2 = C(); // Error: Private constructor }
Surprisingly, this code fails to compile due to the private default constructor. However, the following code:
class C { C() = default; }; int main() { C c{}; // Compiles auto c2 = C{}; // Compiles }
compiles successfully.
The reason for this peculiar behavior lies in the C standard. According to 8.4.2/5 [dcl.fct.def.default], a function is not user-provided if it is explicitly defaulted on its first declaration. Therefore, in our initial example, the default constructor is not user-provided.
This lack of user-provided constructors makes the class C an aggregate as per 8.5.1/1 [dcl.init.aggr], which:
For aggregates, the braced-init syntax is considered a constructor call and not a declaration, which is why it succeeds in the latter code snippet.
The above is the detailed content of Why Does a Private Default Constructor Prevent Object Creation in C But Braced Initialization Works?. For more information, please follow other related articles on the PHP Chinese website!