Initialize the array inside the class

Assume I declare an array in the class header file:

class A{

private:

int a[3];

};

Then I try to initialize it in constructor. It seems I can only assign value to the array element by element like:

A::A()
{
a[0] =1;
a[1] =3;
a[2] =7;
}


Is there any better approaches to initialize the array>

Thanks in advance.
You can use an initializer list:

1
2
3
4
5
6
7
8
9
10
11
class Thing
{
  int x;
  int arr[3];

  Thing( void )
    : x( 10 )
    , arr{ 1, 2, 3}
  {
  }
};
If the values are magic numbers (i.e. their definition is completely arbitrary), this is simple:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//header
class A{
    static const int magic_numbers[3];
    int a[3];
public:
    A();
};

//source
const int A::magic_numbers[] = {
    1,
    3,
    7,
};

A::A(){
    std::copy(magic_numbers, magic_numbers + 3, this->a);
}
Note, however, that filling a variable array with magic numbers is a warning sign that you're doing something wrong. What are you using A::a for?
Topic archived. No new replies allowed.