Home > Backend Development > C++ > Why Can a Private Default Constructor Be Implicitly Invoked in C ?

Why Can a Private Default Constructor Be Implicitly Invoked in C ?

Susan Sarandon
Release: 2024-11-12 04:30:02
Original
1005 people have browsed it

Why Can a Private Default Constructor Be Implicitly Invoked in C  ?

When is a Private Constructor Not a Private Constructor?

In C , declaring a default constructor private may seem like a straightforward way to prevent object instantiation. However, surprisingly, a private default constructor can still be invoked implicitly.

Question:

Consider the following code:

class C {
    C() = default;
};

int main() {
    C c; // error: default constructor private
    auto c2 = C(); // error: default constructor private
}
Copy after login

Why does the constructor appear to be private but can be called implicitly with brace initialization?

Answer:

The key lies in the C 14 specification. A user-provided constructor is one that is explicitly declared without being defaulted or deleted. Since C's default constructor was explicitly defaulted on its first declaration, it is not considered user-provided.

As a result, C lacks user-provided constructors and becomes an aggregate, according to 8.5.1/1 of the specification. An aggregate is defined as a class with no private or protected non-static data members, no base classes, no virtual functions, and no user-provided constructors. This explains why brace initialization can successfully create objects of C, despite the default constructor being technically private.

The above is the detailed content of Why Can a Private Default Constructor Be Implicitly Invoked 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