Home > Article > Backend Development > Can Arrays Be Initialized in a Constructor's Member Initializer List?
Member Array Initialization in Constructors
Consider the following C class:
class C { public: C() : arr({1, 2, 3}) {} // C() : arr{1, 2, 3} {} private: int arr[3]; };
The code attempts to initialize the arr array member in the constructor's member initializer list. However, it fails to compile.
Questions:
Answers:
1. Array Initialization in Constructors
Yes, it is possible to initialize an array in a constructor's member initializer list. However, it requires an intermediary structure:
struct A { int foo[3]; A(int a, int b, int c) : foo{a, b, c} {} }; class C { public: C() : foo(A(1, 2, 3)) {} private: A foo; };
2. C 03 Standard
The C 03 standard does not explicitly address the initialization of arrays in member initializer lists. However, the general rules of direct initialization forbid initializing an array with braces.
3. C 11 List Initialization
C 11 introduced list initialization, which allows direct initialization of arrays using braces:
class C { public: C() : arr{1, 2, 3} {} private: int arr[3]; };
In this case, the syntax using braces directly after the array name is valid and initializes the array in the constructor's member initializer list.
The above is the detailed content of Can Arrays Be Initialized in a Constructor's Member Initializer List?. For more information, please follow other related articles on the PHP Chinese website!