Please excuse me if this is silly.. I do want a clear picture of how we can use a singleton class?? I do read many answers here. But I didn't got anything clear. I need a simple program explaining singleton class. Please give me the explanation of each and every line of code also.. Please. Thank you.

2 Years
Discussion Span
Last Post by tapananand

Here is how you make a singleton class in C++:

class singleton
    static singleton* objRef; //will store reference to the only object.
        cout<<"Private Constructor"<<endl;
        singleton* getObject() //used to get reference to the only object.
            if(objRef == NULL)
                objRef = new singleton(); // can call constructor from here
            return objRef;

singleton* singleton::objRef = NULL;

1. Constructor is private, so we can't create objects from outside, but only from memeber functions.
2. From outside you can use the getObject public member function. What this does is using the objRef static variable, checks if an object has been created if it has been return its pointer else make new object and return it.
So you'll get the reference like this:
singleton* ptr = singleton::getObject();

One thing that I can think of is: a thread controller which creates threads for you, mangaes coordination between them using semaphores. But you don't wanna have two objects of this as you haven't written code for synchronization with threads created by the other object, you can't access them.

Refer this for more.

Edited by tapananand

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.