Home > Backend Development > C++ > body text

Can you initialize an array in a C constructor initializer list?

Patricia Arquette
Release: 2024-11-16 12:41:03
Original
609 people have browsed it

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];
};
Copy after login

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};
Copy after login

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;
};
Copy after login

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} { }
};
Copy after login

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!

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