Link to home
Start Free TrialLog in
Avatar of madhusrj
madhusrj

asked on

Give me a best example for a sigleton class usage

A singleton class is  a class which is having only one object at any time, pls give where it can be useful and how internally it matains .
ASKER CERTIFIED SOLUTION
Avatar of KangaRoo
KangaRoo

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of KangaRoo
KangaRoo

An alternative implementation for GetIt:

Singleton& SingleTon::GetIt()
{
     static Singleton the_object;
     return the_object;
}

This has the advantage that it will only be instantiated if it is actually used. It also asures you that it will exist when used.
That seems like an answer.

one additional point.  The singleton should have a private constructor and destructor, this prevents the user from creating additional instances of the singleton.  

Also there are other variations in the way to impliment signletons, but that is the basic idea.
How would a client call it then?

Singleton *s = Singleton::GetIt();
doesn't work.
That version doesn't return a pointer, it returns a reference. so it wouldd be

Singleton &s = Singleton::GetIt();

(If it returned a pointer, which could be done) your code would have worked.)