Home > Backend Development > C++ > Can Arrays Be Initialized in a Constructor's Member Initializer List?

Can Arrays Be Initialized in a Constructor's Member Initializer List?

DDD
Release: 2024-11-18 11:21:02
Original
513 people have browsed it

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

The code attempts to initialize the arr array member in the constructor's member initializer list. However, it fails to compile.

Questions:

  1. Is it possible to initialize an array in a constructor's member initializer list?
  2. What does the C 03 standard state about this situation?
  3. Does C 11 list initialization address this issue?

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template