Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Static Variable in Class

Tags:

c++

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?

like image 807
Erik W Avatar asked Feb 23 '26 14:02

Erik W


1 Answers

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();
like image 53
qeadz Avatar answered Feb 25 '26 03:02

qeadz