C++ class static struct member definition

I have not found a way to initialize the class member succesfully inside the constructor and I can not figure out why.

I have a header file:

#pragma once

struct STATE_MOUSE {
  bool moving;
  int left_button;
  int right_button;
  int middle_button;
  bool scroll_up;
  bool scroll_down;
};

class Message {
private:
  static STATE_MOUSE state_mouse;
public:
  Message();
  ~Message();
};

Then I have a source file:

#include "message.hpp"

STATE_MOUSE Message::state_mouse = {false, 0, 0, 0, false, false};

Message::Message() {
  //Would like to initialize state_mouse here somehow.
}

Message::~Message() {

}

Now to the issue. This set up seems to work. However I am used to initialize members inside a constructor and I have not found a way to do that with this static struct member.

The following method does not work, could someone explain why?

state_mouse.moving = false;

Upvotes: 4

Views: 5703

Answers (2)

GAVD
GAVD

Reputation: 2134

Static member variables are not associated with each object of the class. It is shared by all objects.

If you declare a static variable inside the class then you should define it in the cpp file, otherwise, you can get error undefined reference.

Note that if the static member variable is of const int type (e.g. int, bool, char), you can then declare and initialize the member variable directly inside the class declaration in the header file.

Upvotes: 1

Akira
Akira

Reputation: 4473

When you declare a member as static it will belong to the class with only one instance and not to the objects of the class, therefore you cannot initialize it inside the constructor. The constructor is a special member function which mainly exists to initialize the non static members of a new object.

Note that a static member is shared by all objects of the class and when an object changes it, the change can be seen from all other objects of the same class. If this is what do you want to achieve, then the method you shown is good.

Upvotes: 3

Related Questions