Hi All
I was going through Singleton design pattern and get to know that objects can be created only by static function of that class and constructors are make private.
My question is, why assignment operators are not made private through which we can create a copy of already existing object.
I tried below code and assignment works, so I have new object sc3.
I know that its referring to memory of sc1 but finally I was able to create object without using static function.
Also, why copy constructor not made as private.
Below is code:
Code:
#include <iostream>
using namespace std;
class Singleton
{
private:
static bool instanceFlag;
static Singleton *single;
Singleton()
{
cout<<"\n Inside Constructor\n";
//private constructor
}
public:
static Singleton* getInstance();
void method();
~Singleton()
{
instanceFlag = false;
}
};
bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;
Singleton* Singleton::getInstance()
{
if(! instanceFlag)
{
single = new Singleton();
instanceFlag = true;
return single;
}
else
{
return single;
}
}
void Singleton::method()
{
cout << "Method of the singleton class" << endl;
}
int main()
{
Singleton *sc1,*sc2,*sc3;
sc1 = Singleton::getInstance();
sc3 = sc1;
sc1->method();
sc3->method();
sc2 = Singleton::getInstance();
//sc2->method();
getchar();
return 0;
}
Thanks