[try Beta version]
Not logged in

 
creating one object

Oct 30, 2012 at 7:03am
Hey guys,
I need to create a class, from which only one object can be created, and if there's an attempt to create another object of this class it gets the address of the first object (they'll both point at the same object..)
Can anyone help? thanks a lot!
Oct 30, 2012 at 9:02am
Oct 30, 2012 at 9:16am
One of possible approaches

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <cassert>

class Singleton
{
public:
   static Singleton * create()
   {
      static Singleton obj;
      return &obj;
   }
private:
   Singleton() {}
};


int main()
{
   Singleton *obj1 = Singleton::create();
   Singleton *obj2 = Singleton::create();

   assert( obj1 == obj2 );
} 


Another way is to have a static member that will keep how many objects are created and to have another static object that will keep address of the first created object. Something as

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Singleton
{
public:
   static Singleton *create()
   {
      if ( count == 0 )
      {
         obj = new Singleton();
      }

      return ( obj );
   }
private:
   Singleton() { count = 1; }
   ~Singleton() { delete obj; obj = 0; count = 0; }
   static size_t count;
   static Singleton *obj;
};
Last edited on Oct 30, 2012 at 9:17am
Oct 31, 2012 at 11:04am
thanks!
Topic archived. No new replies allowed.