Home > Backend Development > C++ > Can Classes with Non-Static Member Initializers Be Aggregates in C 14?

Can Classes with Non-Static Member Initializers Be Aggregates in C 14?

Susan Sarandon
Release: 2024-11-29 03:50:13
Original
520 people have browsed it

Can Classes with Non-Static Member Initializers Be Aggregates in C  14?

C 11 Aggregate Initialization for Classes with Non-Static Member Initializers

In C 11, structures and classes with user-defined constructors and private or protected non-static data members are not considered aggregates. Historically, this was also the case for classes with non-static member initializers, even though they lacked user-defined constructors.

However, in C 14, this restriction was removed. Now, classes with non-static member initializers can still be aggregates, as long as they meet the other requirements for aggregates:

  • No user-defined constructors
  • No private or protected non-static data members
  • No base classes
  • No virtual functions

For example:

struct A
{
  int a = 3;
  int b = 3;
};

int main()
{
  A a{0, 1}; // This is now allowed in C++14
  return 0;
}
Copy after login

This change was motivated by the desire to align the behavior of aggregate initialization with intuition. In-class initializers are essentially equivalent to user-defined constructors, but it is counterintuitive for them to prevent a class from being an aggregate.

Since G 5.0, C 14 aggregates with non-static data member initializers have been supported using std=c 1y or -std=c 14.

The above is the detailed content of Can Classes with Non-Static Member Initializers Be Aggregates in C 14?. 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