How do I write code that allows to create only one instance of a class?

#include <iostream.h>
class sample  
{
         static sample *ptr ;
    private:
         sample( ){}
    public:
         static sample* create( )
         {
                   if ( ptr == NULL )
                       ptr = new sample ;
                   return ptr; 
         } 
 } ;
 sample *sample::ptr = NULL ;
 void main( )
{
      sample *a = sample::create( ) ;
      sample *b = sample::create( ) ;
}

Here, the class sample contains a static data member ptr which is a pointer to the object of same class. The constructor is private which avoids us from creating objects outside the class. A static member function called create( ) is used to create an object of the class. In this function the condition is checked whether or not ptr is NULL, if it is then an object is created dynamically and its address collected in ptr is returned. If ptr is not NULL, then the same address is returned. Thus, in main( ) on execution of the first statement one object of sample gets created whereas on execution of second statement, b holds the address of the first object. Thus, whatever number of times you call create( ) function, only one object of sample class will be available. 

No comments:

Post a Comment