Home > Backend Development > C++ > Can C Constructors Initialize Arrays Directly in Member Initializer Lists?

Can C Constructors Initialize Arrays Directly in Member Initializer Lists?

Susan Sarandon
Release: 2024-11-14 12:59:02
Original
513 people have browsed it

Can C   Constructors Initialize Arrays Directly in Member Initializer Lists?

Initializing Array Members in Constructor Initializer Lists

The inability to initialize arrays in constructors using member initializer lists raises questions regarding the underlying rules and possible solutions.

C 03 Standard and Aggregate Initialization

The C 03 standard prohibits the use of direct initialization for aggregate types, including arrays, in member initializer lists. Direct initialization refers to using the constructor directly with parentheses, as seen in the provided code snippets.

Boost::array as a Solution

An alternative approach is to use a struct that encapsulates the array. By defining a constructor within the struct, you can initialize the array upon object creation. This is similar to the approach taken by the Boost::array library.

C 11 List Initialization

C 11 introduced list initialization, which allows for direct initialization of aggregates, including arrays, in member initializer lists. However, the syntax mentioned in the question is incorrect. To use list initialization, you must enclose the array elements within braces:

class C
{
public:
    C() : arr{1, 2, 3} {}
};
Copy after login

This syntax correctly initializes the arr array within the constructor.

The above is the detailed content of Can C Constructors Initialize Arrays Directly in Member Initializer Lists?. 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