Friday, June 29, 2012

Singleton implementation in c++ !!

Below is the implementation of Singleton in C++.
#include<iostream>
using namespace std;

class single
{
    private:
        static single *ptr;
        single()
        {
        }
    public:
        static single* getInstance();
};

single* single::getInstance()
{
    if(ptr==NULL)
    {
        ptr = new single();
        cout<<"creating the instance and address is "<<ptr<<endl;
    }
    else
    {
        cout<<"instance already created address  is "<<ptr<<endl;
        return ptr;
    }
}
single* single::ptr=NULL; //initialising the static variable

int main()
{
    single *s,*ss,*sss;
    s=single::getInstance();
    ss=single::getInstance();
    sss=single::getInstance();
}

No comments:

Popular Posts