We can create singleton class using :
- A static method or
- By overloading "new" operator for that class.
Expand|Select|Wrap|Line Numbers
- #include<iostream.h>
- #include<conio.h>
- #include<alloc.h>
- class iSingleton
- {
- static iSingleton *sptr; //this pointer points to object of the class
- public:
- iSingleton() //public constructor
- {
- sptr=this;
- }
- void *operator new(size_t); //overload new operator for class which is to be made iSingleton.
- };
- iSingleton *iSingleton::sptr=NULL; //initialize pointer to NULL
- void *iSingleton::operator new(size_t s)
- {
- if(sptr!=NULL) //if already one object is created return reference to same object
- return sptr;
- else
- return malloc(s); //else allocate memory for one (first) object
- }
- int main()
- {
- clrscr();
- iSingleton *sptr1=new iSingleton; //first object created
- iSingleton *sptr2=new iSingleton; //second object created
- if(sptr1==sptr2)
- cout<<"\nGiven class is a Singleton class.";
- else
- cout<<"\nGiven class is not a Singleton class.";
- getch();
- return 0;
- }