Ben
Ben

Reputation: 16669

initialise const array inside class

In Visual C++, how can I initialise a constant array inside of a class?

This is an example of how to do it outside of a class:

const char k_colors[] = 
{ 
    'R', 
    'G', 
    'B',
};

Now how do I need to change that? (I tried putting static in front of it, which didn't work)

Edit: You're right, I should just use single characters.

Upvotes: 0

Views: 763

Answers (4)

Anirudha
Anirudha

Reputation: 32797

I think you can initialize through the constructor initializer list

Refer here

Also the char should be char*

Extract from the above link:

prior to C++11 you need to do just this to default-initialise each element of the array:

: k_colors()

With C++11 it is more recommended use uniform initialisation syntax:

: k_colors{ }

And that way you can actually put things into the array which you couldn't before:

: k_colors{"red","green"}

Upvotes: 0

tozka
tozka

Reputation: 3451

In C++11 you can use the constructor initializer list as mentioned

class A {
    const int arr[2];

    // constructor
    A() 
    : arr ({1, 2}) 
    { }
};

Or you can use static const array

In header file:

class A {
    static const int a[2];
    // other bits follow
};

In source file (or in separate place from the declaration above)

const int A::a[] = { 1, 2 }; 

Of course you can always use std::vector<int> and for loop as well.

Upvotes: 1

hmjd
hmjd

Reputation: 121971

I tried putting static in front of it, which didn't work

You can't initialise the static member array (or any member array) inside the class definition. Do it outside of the class definition:

class X
{
    static const char* k_colors[3];
};

const char* X::k_colors[] = { "Red", "Green", "Blue" };

Upvotes: 3

Yuushi
Yuushi

Reputation: 26040

If you want it to be static, you'll need to initialize it outside the class:

class foo
{
public:
    static const char k_colors[3];
    foo() { }

};

const char foo::k_colors[] = {'a', 'b', 'c'};

Also, you probably want it to be a const char *[] since it looks like you're trying to initialize strings, so it'd be:

const char *foo::k_colors[] = {"Red", "Green", "Blue"};

Upvotes: 3

Related Questions