Home > Backend Development > C++ > body text

Can a C class with non-static member initializers be an aggregate?

Mary-Kate Olsen
Release: 2024-11-10 03:58:02
Original
690 people have browsed it

Can a C   class with non-static member initializers be an aggregate?

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

In C 11, a class or struct is considered an aggregate if it meets specific criteria, including having no user-defined constructors, no brace-or-equal initializers for non-static data members, and no private or protected non-static data members.

However, in standard C 11, adding non-static member initializers to a class or struct changes its status as an aggregate. This is because member initializers are similar to user-defined constructors, which disqualifies the class or struct from being an aggregate. This change in definition can lead to unexpected behavior.

In the example provided:

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

A a{0,1}; // ???
Copy after login

The class A is no longer considered an aggregate due to the presence of in-class member initializers. As a result, the aggregate initialization A a{0,1}; is invalid.

This behavior was revised in C 14, where the presence of non-static member initializers no longer prevents a class or struct from being an aggregate. Therefore, in C 14, the aggregate initialization of A is valid.

It is important to note that the C standard has undergone changes, and it is essential to check the latest versions of the standard or use a compliant C 14 or later compiler to ensure correct interpretation of code involving aggregate initialization and non-static member initializers.

The above is the detailed content of Can a C class with non-static member initializers be an aggregate?. 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