How to write a program for singleton class?

Showing Answers 1 - 9 of 9 Answers

Samatha Reddy

  • Jan 24th, 2007
 

declare a pointer as static variable of class, and return pointer to that.eg: class singleton{static singleton p;public : singleton() {};singleton get_object(){return &p;}};this should about do it..

  Was this answer useful?  Yes

class singleton

{

     private:

     singleton()

     { }


     public:

     static singleton* GetMe()

     {

     return (new singleton());

     }

}


main()

{

     singleton *obj = singleton::GetMe();

}

  Was this answer useful?  Yes

Both the above methods doesn't meet the purpose. Try thisclass singleton{ private: /*add what ever data members necessary*/ static singleton* obj; singleton() { } public: /*add what ever data members necessary*/ static singleton* GetObject() { if(obj == NULL) { obj = new singleton; } return obj; }};singleton::obj = NULL;main(){ singleton *object = singleton::GetObject();}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions