3

I want to have static variables in a C++ class (const if possible). How can I set their value? I want them to be dynamically allocated.

Here is my class:

class Color
{
public:
    static int* BLACK;
    static int* WHITE;
};

I have done this, which seems to be working fine:

int* Color::BLACK = new int[3];
int* Color::WHITE = new int[3];

But how do I set their value after that? And is it possible to make them const?

2
  • 1
    Why do you need them to be dynamically allocated? And by "set their value", do you mean re-assign a newly allocated array, or access the values of the array? Commented Mar 26, 2015 at 18:45
  • Color::BLACK[0] = 0; (etc) at the start of main() or somewhere that the app is initialized? And by const, do you mean int* const or int const * const? Commented Mar 26, 2015 at 18:45

1 Answer 1

1

It's probably better to not have colors dynamically allocated in the first place because it'll prevent the compiler from being able to do various optimizations. Ideally:

class Color
{
public:
  static int const BLACK[3];
};
int const Color::BLACK[3] = {0,0,0};

However if you do want them on the heap then it depends on whether you want the pointer to be const, the values const or both!

If you want the pointer and values to be const then you may have to do this:

class Color
{
public:
  static int const * const BLACK;
};
int const * const Color::BLACK = new int[3]{0,0,0};

To be honest I am unsure of what context would demand the pointer and allocation. It seems unnecessary.

EDIT: For a pre-C++11 compilers you could do something like this:

int * make_black()
{
  int * color = new int[3];
  color[0] = color[1] = color[2] = 0;
  return color;
}

class Color
{
public:
  static int const * const BLACK;
};
int const * const Color::BLACK = make_black();
Sign up to request clarification or add additional context in comments.

3 Comments

Did you try this? Visual Studio doesn't allow the {0,0,0} initializers of the pointer style declaration.
VS2013 onwards does as it is a newer C++ feature. However it now appears that you're using an earlier version. I am not aware of a way to do the initialization of the allocated memory without this feature pre C++11. You might have to make the pointed-to type non-const and init the values when your app begins execution.
@Bruce on further consideration if you relaxed the desire to allocate on the line where Color::BLACK (for example) is initialized, you could do it through a factory function. I've amended the answer.

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.