seenmycorpseanywhere
seenmycorpseanywhere

Reputation: 748

c++: Proper way to initialize static fields of member struct

I got this:

// mouse.h
class Mouse {
  private:
    struct Pos {
      static GLfloat x;
      static GLfloat y;
    };    
    static Pos last;
}

and this:

// mouse.cpp
// 1)
Mouse::Pos Mouse::last = {};
// 2)
Mouse::Pos Mouse::last = { 0.0, 0.0 };
// 3)
Mouse::last.x = 0.0f;
Mouse::last.y = 0.0f;

1), 2) and 3) are the attempts I've made at initializing that thing. I understand that the header should declare that last is static, and that the source should initialize it, but something has been wrong with all my attempts. Could someone please tell me the correct way to do such a thing? Am I missing some very important point? Is this nonsense? It is important that the fields are static. Thanks.

Upvotes: 0

Views: 128

Answers (2)

Jose Palma
Jose Palma

Reputation: 756

You don't need to declare Pos content as static.

// mouse.h

class Mouse {
  private:
    struct Pos {
      GLfloat x;
      GLfloat y;
    };    
    static Pos last;
}

Mouse::Pos Mouse::last = { 0.0, 0.0 };

This should work too

Upvotes: 7

Vittorio Romeo
Vittorio Romeo

Reputation: 93274

It is important that the fields are static.

Then last will not have any state. It will simply refer to the static x and y values inside Mouse::Pos.

#include "mouse.h"

GLfloat Mouse::Pos::x = 10;
GLfloat Mouse::Pos::y = 10;

Mouse::Pos Mouse::last{};

wandbox example


The following asserts pass:

assert(Mouse::last.x == 10);
assert(Mouse::last.y == 10);

Upvotes: 2

Related Questions