I have created below singleton class and defined copy constructor and assignment operator as a private. When I invoke copy constructor or assignment operator, it does not call copy constructor and assignment operator(Maybe due to statically object creation). So my question is why singleton design pattern allows creating copy of object or assigning new object(which violates basic requirement of creating single instantiation of a class) form previously created object even they are declared private in a class?
Consider below code for details:-
#include <iostream>
#include "conio.h"
class singleton
{
static singleton *s;
int i;
singleton()
{
};
singleton(int x):i(x)
{ cout<<"\n Calling one argument constructor";
};
singleton(const singleton&)
{
cout<<"\n Private copy constructor";
}
singleton &operator=(singleton&)
{
cout<<"\n Private Assignment Operator";
}
public:
static singleton *getInstance()
{
if(!s)
{
cout<<"\n New Object Created\n ";
s=new singleton();
return s;
}
else
{
cout<<"\n Using Old Object \n ";
return s;
}
}
int getValue()
{
cout<<"i = "<<i<<"\n";
return i;
}
int setValue(int n)
{
i=n;
}
};
singleton* singleton::s=0;
int main()
{
// Creating first object
singleton *s1= singleton::getInstance();
s1->getValue();
singleton *s4=s1; // Calling copy constructor-not invoking copy ctor
singleton *s5;
s5=s1; // calling assignment operator-not invoking assign ope
//Creating second object
singleton *s2=singleton::getInstance();
s2->setValue(32);
s2->getValue();
//Creating third object
singleton *s3=singleton::getInstance();
s3->setValue(42);
s3->getValue();
getch();
return 0;
}
Am I missing something or my understanding is wrong.
Please help in this. Thanks in advance.