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.

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

class singleton
{
    static singleton* objRef; //will store reference to the only object.
    singleton()
    {
        cout<<"Private Constructor"<<endl;
    }
    public:
        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;

Explaination:
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();

Uses:
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 2 Years Ago by tapananand

This article has been dead for over six months. Start a new discussion instead.