This question already has an answer here:
- Single class instance C++ 3 answers
Is there any way to allow only one instance of a class in C++? If there is, please expain to me. Thank you.
This question already has an answer here:
Is there any way to allow only one instance of a class in C++? If there is, please expain to me. Thank you.
This is the singleton pattern. You can achieve this via a public static attribute and a private constructor:
class Singleton {
public:
static Singleton * const singleton;
private:
Singleton(void) {}
};
Singleton * const Singleton::singleton = new Singleton();
Edit: Good point from Dan Watkins; If you really want to be draconian about it, you can disallow copy and assignment by also explicitly declaring those methods private:
private:
Singleton(void) {}
Singleton(Singleton& other) {}
Singleton& operator=(Singleton& other) {}