jeudi 21 mai 2015

what is the exact use and implementation of singleton class?

I know the singleton class does not allow to create more than one object. but as per my below code i can create as many objects as possible.

class Singleton
{
  private :
   static Singleton *m_Instance;
   Singleton()
   {
     cout<<"In defailt constructor"<<endl;
   }
   Singleton(int x)
   {
      i = x;
      cout<<"in param const"<<endl;
   }
 public:
   static int i;
   static Singleton* createInstance()
   {
      if(!m_Instance)
        m_Instance = new Singleton(20);
      Singleton sing;
      return m_Instance;
   }
};
int Singleton::i=0;
Singleton* Singleton::m_Instance = NULL;
int main()
{

    Singleton *pt = Singleton::createInstance();
    return 1;
}

Here I am able to create an object in the static function (as i can access constructor within the class) then where is the concept of Single object?

Aucun commentaire:

Enregistrer un commentaire