Home >Backend Development >C++ >Can you initialize an array in a C constructor initializer list?
Initializing Array Members in Constructor Initializer Lists
C provides the ability to initialize class members using a member initializer list in the constructor. However, initializing an array member in this way can encounter compilation errors.
The code snippet below demonstrates the attempted initialization of an array member in a constructor initializer list, but fails to compile:
class C { public: C() : arr({1,2,3}) { // doesn't compile } /* C() : arr{1,2,3} // doesn't compile either } */ private: int arr[3]; };
The reason for this issue lies in the restrictions on initializing arrays. Arrays can only be initialized through assignment syntax ('='), as seen in the following example:
int arr[3] = {1,3,4};
Questions and Answers:
1. How to Initialize an Array in Constructor Initializer Lists?
To initialize an array in a constructor initializer list, one must use a struct that contains the array as a member variable:
struct ArrStruct { int arr[3]; ArrStruct() : arr{1,2,3} { } }; class C { public: C() : arr_struct(ArrStruct()) { } private: ArrStruct arr_struct; };
This approach involves creating a separate struct to hold the array and then initializing the struct within the constructor.
2. C 03 Standard and Array Initialization
The C 03 standard does not explicitly address the initialization of aggregates (including arrays) in constructor initializer lists. The invalidity of the code in the original example stems from general rules prohibiting direct initialization of aggregates via initializer lists.
3. C 11 List Initialization
C 11 list initialization provides a solution to this problem. However, the syntax in the original question is incorrect. The correct syntax is:
struct A { int foo[3]; A() : foo{1, 2, 3} { } };
Using curly braces directly triggers the list initialization feature of C 11.
The above is the detailed content of Can you initialize an array in a C constructor initializer list?. For more information, please follow other related articles on the PHP Chinese website!