Static Keyword in Classes

Started by
4 comments, last by SiCrane 16 years, 2 months ago
I had a question regarding the usage of the static keyword in C++. Basically, what I am attempting to achieve is this- I am constructing a mouse class that will handle mouse input, and I was trying to make the class itself hold a static member that is of the mouse class itself, so that there would be no need for a global mouse object. For example:

private:
     static CMouse m_mouse;

public:
     // Accessor method
     static CMouse GetMouse() { return m_mouse; }
My problem is that it gives me an error when I try to call a function, in the main() of the program like so:

int main()
{
     CMouse::GetMouse().Init();
}
The error says that the symbol "m_mouse" cannot be found. I think I understand why this happens, but can anyone tell me how to fix it (because I would prefer this to a global mouse object)?
Advertisement
I just realized a easier solution to this problem. If anyone has any alternatives, and would like to post, I will take those into consideration. Thanks.
You're basically describing a concept known as a "singleton".

I usually prefer to implement them like this:
class MyClass{public:  MyClass& Instance();private:  MyClass(){}//make the constructor private so no-one else can make an instance};MyClass& MyClass::Instance(){//create the instance as a static variable inside a function so it gets initialised on first use  static MyClasss_Instance;  return s_Instance;}
Congratulations, you've just created a singleton. Now learn why it's a Bad Thing™.
Despite what many say, there's nothing wrong with the singleton pattern itself.

The controversy usually arises when the pattern is used when it is not actually required, or when it is implemented in a bad way.

E.g.
It is possible (but rare) that a class is required to only ever have one instance, otherwise errors may occur. When faced with such a requirement, the singleton pattern is an obvious answer.
However, a lot of the time creating two instances of a class may not be desired - but doing so will not cause errors, so there is actually no need to utilise the singleton pattern here (and doing so may be a sign of a bad design that makes use of global variables)...

Some 'bad' implementations of singletons may be the source of bugs due to misunderstandings of static initialisation order, or race conditions in multi-threaded code (i.e. incorrect double-checked locking).
To answer the original question, when you declare a static variable in a class, you still need to define it. So you need to put
CMouse CMouse::m_mouse;

In one source file at namespace scope (in the same namespace as the CMouse definition).

For more details see orgfiles.

This topic is closed to new replies.

Advertisement