Initialization of const array member

Can a class contain a const array member, like
1
2
3
4
5
6
7
class A{
public:
    A();
    ~A();
private:
    const int array[10];
};

If so, how to initialize it?
Yes, you can do that, but initializing the array is tricky. One way to do it is this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;

struct Array
{
    int arr[10];

    Array(int * a)
    {
        for (int i=0; i<10; i++) arr[i]=a[i];
    }
};

class A
{
public:
    A(int * a):array(a){}
    ~A(){}
//private:
    const Array array;
};

int main()
{
    int arr1[10]={1,2,3,4,5,6,7,8,9,10};
    int arr2[10]={1,3,5,7,9,-2,-4,-6,-8,-10};

    A a(arr1);
    A b(arr2);

    int i;
    for (i=0; i<10; i++)
        cout << a.array.arr[i] << ' ';

    cout << endl;
    for (i=0; i<10; i++)
        cout << b.array.arr[i] << ' ';

    cout << endl;
    cout << "hit enter to quit..." << endl;
    cin.get();

    return 0;
}
Last edited on
It can also be made to be static if your instances can all share the same values. You can also use the enum concept to declare collections of related constants. To be honest I have not ever seen a situation where a non-static const array member was needed. However, what m4ster r0shi did was a pretty creative work around.
Many thanks! I used static array in my code, but m4ster r0shi really gives me a new understanding.
Thank you.
Topic archived. No new replies allowed.