Initialize string array in a class

After googling, I finally know how to initialize a string array in a class, which looks like this:

1
2
3
4
5
6
7
8
9
10
// number.h
class number
{
private:
  static const string num[2];
}

// number.cpp

const string number::num[2] = {"one", "two"};


However, I'm still wondering why we can't initialize it in the constructor, which looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

// number.h
class number
{
private:
  static const string num[2];
public:
  number();
}

// number.cpp

number::number()
{
  const string number::num[2] = {"one", "two"};

}


closed account (SECMoG1T)
your string is a static members, meaning that it will be created immediately the program begins executing , that is long before any instance of your class can be created through your constructors.

static members cannot be intialized via constructors.

anyway i also learnt that the other day haha.

http://www.icce.rug.nl/documents/cplusplus/cplusplus08.html
Last edited on
Topic archived. No new replies allowed.