Home > Backend Development > C++ > Why Does Using Curly Braces Allow Initialization of a Class with a Private Default Constructor in C ?

Why Does Using Curly Braces Allow Initialization of a Class with a Private Default Constructor in C ?

Mary-Kate Olsen
Release: 2024-11-20 03:06:02
Original
164 people have browsed it

Why Does Using Curly Braces Allow Initialization of a Class with a Private Default Constructor in C  ?

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
}
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template