Sign in to follow this  
e_v0id

Static Keyword in Classes

Recommended Posts

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)?

Share this post


Link to post
Share on other sites
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;
}

Share this post


Link to post
Share on other sites
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).

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this