Problem
Implement a class, restricting the instantiation of a class to one object
Solution
#include <iostream>
using namespace std;
class singleton
{
private:
singleton() {};
static singleton* _instance;
public:
static public singleton* get_instance()
{
if(_instance == NULL){
_instance = new singleton();
}
return _instance;
}
};
singleton* singleton::_instance = NULL;
int main(int argc, char* argv[])
{
singleton *s = singleton::get_instance();
cout << s << endl;
s = singleton::get_instance();
cout << s << endl;
return 0;
}
Output
00396440
00396440