In the Singleton pattern why is that we have to use a static object and not a global object?
I tried the following
class Singleton;
Singleton* instance1 = NULL;
class Singleton
{
private :
Singleton()
{
}
//static Singleton* instance1;
public:
static Singleton* getinstance()
if(instance1== NULL)
{
instance1 = new Singleton();
}
return instance1;
void Dispaly()
{
}
~Singleton()
{
}
};
When I compile this code I get the error “multiple definition of instance1”
Can anyone please give a plausible reason for this?
If you make it a global object, then everyone has access to it, and anyone can use it without calling
getInstance(). If so, then what is the purpose ofgetInstance()then? First time, you will call it to create the instance, then you wouldn’t be required to callgetInstance(), since after the first call, you can directly useinstance.A
privatestatic instance gives you more control how it can be accessed: only through by callinggetInstance().Now why you get
multiple definition of instanceerror when compiling your code? Its because you’ve defined the global object in the header file itself, which is included in multiple.cppfiles. This causes multiple definitions of the object, one definition in each translation unit (.objfile).What you actually should be doing is this:
And then define the
staticmember in the.cppfile as: