0

I'd written an event handler mechanism that works quite well. So I extended it to be more generalised and wrote an event handler to give me the keyboard state:

class KeybdHandler : public EventHandler<KeybdHandler> { private: Keyboard _keybd; public: void SetEvent( const Keyboard::KeyEvent & evt ) { Keyboard::KeyEvent e = evt; // event holds the new keystate Notify(&e); // keystate is saved to keyboard _keybd.SetKey(e._Key, e._bKeyDown); } Keyboard & GetKeybd() { return _keybd; } }; static KeybdHandler g_evtKeybd; 

The KeybdHandler::Keyboard variable holds an array that denotes the keyboard state (e.g. one entry per key and bool variable denoting keydown or keyup).

So I create a static instance of this KeybdHandler class.

But when I call g_evtKeybd.GetKeybd(), the keyboard state is always empty / blank / all in keyup state.

When I make the KeybdHandler::Keyboard variable static, GetKeybd() returns a Keyboard object with state saved.

Why must the Keyboard variable be static if the containing object is static?

EDIT: Just want to clarify that SetEvent is always called through the static variable:

g_evtKeybd.SetEvent( Keyboard::KeyEvent((int)key, true)); 

EDIT2: I'm not certain if it's relevant. The KeybdHandler class is in a static library and linked to from another executable.

3
  • Inheriting from templates is not something I do often, so excuse me if this is irrelevant or wrong, but from the definition of the class, KeybdHandler inherits a template of type KeybdHandler (same class). Would this not mean that you've then got multiple versions of the same class variables, so the one you're setting is not the one you're retrieving? If so, print out the address of the non-static variables at the get and set accessors and see if they match. Commented May 22, 2013 at 10:51
  • @Merlin069, the parent class isn't really relevant, see en.wikipedia.org/wiki/Curiously_recurring_template_pattern Commented May 22, 2013 at 11:02
  • 1
    That's really interesting. Thanks for the link. Commented May 22, 2013 at 12:14

1 Answer 1

1

You declared g_evtKeybd as a global static variable. In this context static has a different meaning. Each compilation unit will have it's own instance of g_evtKeybd which is probably not what you intended. As static members are shared by all instances of a class, all of them will return the same, even though you have multiple instances (hiding your actual mistake).

Sign up to request clarification or add additional context in comments.

1 Comment

I think you hit the nail on the head there. Thanks Joe. I think I'll have to make Singletons out of the keybd and mouse handlers :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.