Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: static initialize an array member, member at a time

I now I can do this in global scope and everything works fine:

const char* Foo::bars[3] = {"a", "b", "c"};

But I want to do this because this is much more clearer and self documenting (especially if you use Enums as the index):

const char* Foo::bars[3];
bars[0] = "a";
bars[1] = "b";
bars[2] = "c";

Is it anyway possible?

I know I can do this inside a function (for example, the class's constructor) but what if the constructor is not called in the start of the program and I want to use the static array? That leads to problems.

like image 392
bittersoon Avatar asked Feb 26 '23 06:02

bittersoon


2 Answers

How about this?

const char* Foo::bars[3] = {
/* Index    Value */
/* 0 */     "a",
/* 1 */     "b",
/* 2 */     "c"
};

I often use this "technique" to make the initialization of arrays of structs look like a self-documenting spreadsheet.

like image 153
Emile Cormier Avatar answered Mar 08 '23 10:03

Emile Cormier


In C++ there is no equivalent of the static Java block.

If you really want to initialize the array automatically, you can create a simple class to do the job:

// in .cpp
class FooInitializer {
public:
    FooInitializer() {
        Foo:bars[0] = "a";
        Foo:bars[1] = "b";
        Foo:bars[2] = "c";
    }
};

static FooInitializer fooInitializer;
like image 21
vz0 Avatar answered Mar 08 '23 09:03

vz0