Wednesday, February 15, 2012

What is singleton in C++?

Singleton is a mechanism to restrict the instance of a class to single/unique. This is useful when only one instance across the application is required. There are different ways to implement. Here is the simple one in C++. To implement this in c++ singleton class should satisfy below points.
  • Constructor should be private, so that only member function can instantiate
  • Static pointer variable of the type same class
  • Static member function like getInstance()
After creating the class, initialize the static variable to NULL and implement the member function. In member function check for the static pointer variable for NULL, if it is NULL create the new Instance other wise return that pointer.
using namespace std;

class single{
static single *ptr; // pointer variable should be static
single() // constructor should be private
static single* getInstance();

single* single::getInstance() // static function definition
ptr = new single(); creating the instance
cout<<"creating the instance and address is "<<ptr<<endl;
cout<<"instance already created and address is "<<ptr<<endl;
return ptr;

single* single::ptr=NULL; // initializing static variable;

int main()
single *s,*ss,*sss;
s=single::getInstance(); // first time creating the instance
ss=single::getInstance(); // returning the same instance
sss=single::getInstance();// returning the same instance


creating the instance and address is 0x4c49010
instance already created address is 0x4c49010
instance already created address is 0x4c49010

In the sampel code , there are three function calls for creating the Instance. from the output, it is clear that first time only it created the instance and remaining two times it returned the existing pointer. All the time address is same in the output, it means only one instance exists.


Unknown said...

why you did not included copy constructor and assignment operator syntaxes under private i ave seen somany codes there is copy and assgin syntaxes

Unknown said...

and why we need to use static key word

Unknown said...

and why pointer variable why not normal variable and why we need to assign ptr to null

Unknown said...

static single* getInstance();
i did not understand why is this
and why we have declared static under private

Chanduthedev p said...

Hi Kumar,

1. Copy constructor or assignment operators are not required for the singleton as it doesn't required object assignment or object passing as parameter.
2. please refer this link for static functions in cpp
3. Singleton needs pointer variable which is dynamically allocated value to have the life time until application terminates. If you use normal variable, it will delete automatically when we come out of that function.


Popular Posts