0

I need to initialize a const int array in a class constructor via initialization list in C++.

  • I know that there is an easy solution of this problem based on using extended initialization list.
  • Still, I want to avoid using -std=c++11 or -std=gnu++11.
  • Obviously, I know from the beginning that its size is 4 and the content is {1, 2, 3, 4}.
Jean
  • 7,505
  • 6
  • 42
  • 58
Hubert Siwkin
  • 395
  • 3
  • 16
  • Because a char is simply a byte, it can hold values in the range 0 to 255 or -128 to 127, depending on whether it is signed or not. – Jack Aidley Apr 07 '13 at 12:01
  • It was a typo :) I corrected it :) – Hubert Siwkin Apr 07 '13 at 12:02
  • 4
    Why do you _need_ to initialize a `const int` array in a class constructor via initialization list with a set of fixed values? Why not just make it a `static` member (seeing as it's contents cannot change and aren't specific to the instance being constructed)? – CB Bailey Apr 07 '13 at 12:08
  • Were it not for your last statement in the question, your query might have teeth, but as-written, Charles' comment addresses it pretty fundamentally. – WhozCraig Apr 07 '13 at 12:15
  • You are right. Using static const member looks like a good idea. – Hubert Siwkin Apr 07 '13 at 12:25

2 Answers2

1

The only way I can conceive doing this while staying out of the C++11 initializer list realm is to bury it in a struct wrapper and value-initialize it in your construct-initializer list:

#include <iostream>
using namespace std;

struct ArrayWrap
{
    int content[4];
    int& operator [](size_t n) { return content[n]; }
    int operator [](size_t n) const { return content[n]; }
};

static const ArrayWrap content = { {1,2,3,4} };


struct MyObj
{
    const ArrayWrap arrwrap;

    MyObj() : arrwrap(content) {}
};

int main(int argc, char *argv[])
{
    MyObj obj;
    for (int i=0;i<4;++i)
        cout << obj.arrwrap[i] << ' ';
    cout << endl;

    return EXIT_SUCCESS;
}

Output

1 2 3 4

It is common in C to bury fixed arrays in structures when returning them from functions by value, and in this case I'm simply exploiting the default copy-ctor of the wrapper struct as-generated by the C++ compiler.

Probably not the ideal solution for what you want, but it does work, and compiles under C++98.

WhozCraig
  • 63,603
  • 10
  • 71
  • 134
0

Well, if you're banning C++11 solutions from the candidate set, then you simply cannot do this.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 369,052
  • 73
  • 620
  • 1,021