0

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.

5
  • 2
    Don't you mean const char* and "Red", etc? Commented Oct 5, 2012 at 7:35
  • 1
    Well that won't work at all, as you are using multiple character literals where it should be only a single character. Do you mean char * and e.g. "Red"? Commented Oct 5, 2012 at 7:36
  • Does your compiler support C++11 features? Commented Oct 5, 2012 at 7:36
  • 1
    If it is the same array in each object, you can make it static and initialize it separately. Commented Oct 5, 2012 at 7:37
  • char should be char* Commented Oct 5, 2012 at 7:42

4 Answers 4

3

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"};
Sign up to request clarification or add additional context in comments.

Comments

3

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" };

Comments

1

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.

Comments

0

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"}

1 Comment

An array? (I think you can in C++11, but you certainly can't in C++03.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.