- Constructor should be private, so that only member function can instantiate
- Static pointer variable of the type same class
- Static member function like getInstance()
#include<iostream>Output:
using namespace std;
class single{
private:
static single *ptr; // pointer variable should be static
single() // constructor should be private
{
}
public:
static single* getInstance();
};
single* single::getInstance() // static function definition
{
if(ptr==NULL)
{
ptr = new single(); creating the instance
cout<<"creating the instance and address is "<<ptr<<endl;
}
else
{
cout<<"instance already created and address is "<<ptr<<endl;
return ptr;
}
}
single* single::ptr=NULL; // initializing static variable;
int main()
{
single *s,*ss,*sss;
s=single::getInstance(); // first time creating the instance
ss=single::getInstance(); // returning the same instance
sss=single::getInstance();// returning the same instance
}
creating the instance and address is 0x4c49010
instance already created address is 0x4c49010
instance already created address is 0x4c49010
In the sampel code , there are three function calls for creating the Instance. from the output, it is clear that first time only it created the instance and remaining two times it returned the existing pointer. All the time address is same in the output, it means only one instance exists.
5 comments:
why you did not included copy constructor and assignment operator syntaxes under private i ave seen somany codes there is copy and assgin syntaxes
and why we need to use static key word
and why pointer variable why not normal variable and why we need to assign ptr to null
static single* getInstance();
i did not understand why is this
and why we have declared static under private
Hi Kumar,
1. Copy constructor or assignment operators are not required for the singleton as it doesn't required object assignment or object passing as parameter.
2. please refer this link for static functions in cpp http://chanduthedev.blogspot.in/2012/02/static-variables-and-static-member.html
3. Singleton needs pointer variable which is dynamically allocated value to have the life time until application terminates. If you use normal variable, it will delete automatically when we come out of that function.
Thanks,
chanduthedev
Post a Comment