Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private static data member in Cpp.. can only be initialized at its definition, yet invalid in-class initialization?

Initializing in the header file i get the following error:

invalid in-class initialization of static data member of non-integral type 'bool [8]'

if i try to initialize in the .cpp, i get:

'bool Ion::KeyboardInput::key [8]' is a static data member; it can only be initialized at its definition

Heres the header:

enum MYKEYS {
    KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_W, KEY_S, KEY_A, KEY_D
};

class KeyboardInput
{
public:
    KeyboardInput();
    ~KeyboardInput();
    static void getKeysDown(ALLEGRO_EVENT ev);
    static void getKeysUp(ALLEGRO_EVENT ev);
    static bool getKey(int keyChoice);

private:
    static bool key[8] = {false, false, false, false, false, false, false, false};
};
like image 640
ollo Avatar asked Jun 18 '12 23:06

ollo


1 Answers

The first error message informs you that it is improper to initialize the static member variable in the header file. The second error message implies you tried to initialize the static member key in your constructor.

A static class member variable needs to be declared inside the class (without initialization) and then defined outside of the class in the .cpp file (sort of like a global variable, except the variable name has the class name included with it).

bool KeyboardInput::key[8];

The definition of the variable may include an initializer. Since you were initializing it to all false, the above definition in your .cpp file is sufficient.

A static class member variable is not too different from a global variable, except that it is scoped by the class name, and can be protected to only be accessible by members of the class (with private), the class's immediate subclasses (with protected), or the class's friends.

like image 196
jxh Avatar answered Oct 21 '22 04:10

jxh