Purpose of having Static object

Can any one tell me what is the purpose of having static object of the same class.


for e.g.

class someObj{
public:
static someObj obj;
};

how the compiler treats this object
For example if you want to have only a single object of type someObject and no one could create another object of this type. In this case you can write

1
2
3
4
5
6
7
8
9
10
class someObj
{
private:
   someObj() {}

public:
   static someObj obj;
};

someObj someObj::obj;

As the constructor is private the client code can not create an object of this type.
Last edited on
Using a static class member like that is a basic way of implementing the singleton pattern
http://en.wikipedia.org/wiki/Singleton_pattern

But the standard form uses a static method rather than a static class member.

1
2
3
4
5
6
7
8
9
10
11
12
class Singleton
{
private:
   Singleton();

public:
   static Singleton& instance()
   {
      static Singleton s_inst;
      return s_inst;
   }
};


Andy

C++ Singleton design pattern
http://stackoverflow.com/questions/1008019/c-singleton-design-pattern
(including interesting links...)
Last edited on
Thank you guys
Topic archived. No new replies allowed.