Be the first to like this
Name : Prasoon Dadhich
USN : 1MS09IS069
using namespace std;
static bool instanceFlag;
static Singleton *single;
static Singleton* getInstance();
instanceFlag = false;
bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;
single = new Singleton();
instanceFlag = true;
cout << "Method of the singleton class" << endl;
sc1 = Singleton::getInstance();
sc2 = Singleton::getInstance();
If we create any object of this class then the static object (player) will be returned and assigned to the new object.
Finally only one object will be there. The point is not how many times something gets executed, the point is, that the work is done by a single instance of the the class. This is ensured by the class method Singleton::getInstance().
As you can see in the above code,Client can access any instance of the singleton only through the getInstance() method.Once an instance is created,the instanceFlag value becomes true and then any further objects pointers created will be given the reference to the same object that has been created.
Also,make sure you notice the presence of a private constructor.This ensures that no new objects of the class are created and that all the class pointers get the same reference to work on.