-1

I want to define a constant array as data member of class in its source file.

The array has 256 elements, and there is no relation between them.

class Foo {
    private: 
    const int myArray[256] = {
        0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0,
        0, 0, 3, 0, 3, 0, 0, 1, 3, 0, 0, 0, 0, 1, 2, 0,
        0, 0, 2, 2, 1, 0, 3, 2, 0, 2, 0, 0, 0, 0, 0, 0,
        0, 4, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 4, 0,
        0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    };
};

My Questions:

1- Is it better to shift the definition of the array to the source file?

2- Is there anyway to define this array in a source file instead of the header that defines the class?

Zingo
  • 600
  • 6
  • 23
  • 1
    Where did you see anything about `static` members being implicitly constant? Nothing at that link says that. Not that you're relying on it, so I'm not really sure how it's relevant. – ShadowRanger Jan 20 '17 at 03:14
  • sorry my bad. constant members are static implicitly – Zingo Jan 20 '17 at 03:15
  • I am just trying to find way to not define this array in header file. – Zingo Jan 20 '17 at 03:20
  • 2
    Okay, so what's your question? You want a better way to initialize it without all the padding? It doesn't exist in C++, C++ hasn't incorporated [C99 designated initializer syntax](https://stackoverflow.com/questions/855996/c-equivalent-to-designated-initializers). Please edit the question to add your actual question, don't dribble it out in comments. – ShadowRanger Jan 20 '17 at 03:21

1 Answers1

3

in the header:

static const int myArray[256];

in the cpp file

const int Foo::myArray[256] = {
    // numbers
};

I'm assuming here you don't need one per class instance.

Regarding the question of where it's better to put it; I would put it in the cpp file, but that's mostly a matter of style.

sp2danny
  • 7,488
  • 3
  • 31
  • 53