Home > Backend Development > C++ > body text

Why Does a Private Default Constructor Prevent Object Creation in C But Braced Initialization Works?

Patricia Arquette
Release: 2024-11-12 20:39:02
Original
714 people have browsed it

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

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

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:

  • Has no user-provided constructors
  • Has no private or protected non-static data members
  • Has no base classes
  • Has no virtual functions

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!

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