Initialize a static member ( an array) in C++

You can, just do this in your .cpp file:

char A::a[6] = {1,2,3,4,5,6};

If your member isn't going to change after it's initialized, C++11 lets you keep it all in the class definition with constexpr:

class A
{
public:
  static constexpr const char a[] = {1,2,3}; // = "Hello, World"; would also work
  static void do_something();
};

Just wondering, why do you need to initialize it inside a constructor?

Commonly, you make data member static so you don't need to create an instance to be able to access that member. Constructors are only called when you create an instance.

Non-const static members are initialized outside the class declaration (in the implementation file) as in the following:


class Member
{
public:
    Member( int i ) { }
};

class MyClass
{
public:
    static int i;
    static char c[ 10 ];
    static char d[ 10 ];
    static Member m_;
};


int MyClass::i = 5;
char MyClass::c[] = "abcde";
char MyClass::d[] = { 'a', 'b', 'c', 'd', 'e', '\0' };
Member MyClass::m_( 5 );

Tags:

C++