top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

C++ : What is the way to define singleton class in C++ ?

+2 votes
507 views

I know the definition of singleton class i.e. a class for which only one object can be defined or initialized. But I want to know all the possible ways to achieve this restriction.

posted Sep 11, 2016 by Neelam

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

The following is the simple example to create singleton class in c++

important steps in creating singleton class are as follows
Make constructor private
Have an instance of the class inside the class itself
Have a static public function to get the instance declared inside the class

class Singleton
{
private :
int x;

static Singleton* s;

Singleton(int n)
{
x=n;
}
public : 

static Singleton getInstance(int n)
{
if(s==NULL)
  s=new Singleton(n);
return *s;
}
//....
};
Singleton Singleton::s=NULL;
int main()
{
Singleton object=Singleton::getInstance(10);
//...
}
answer Sep 11, 2016 by Vivek B
...