Reputation: 9634
In this, i am trying to copy singleton object to another object. Though i have overridden = operator, its giving me some problem. Kindly help.
class singleTon
{
public:
static singleTon* InitInstance()
{
if(singleTonObjPtr== NULL)
{
singleTonObjPtr = new singleTon;
}
return singleTonObjPtr;
}
singleTon* getObject()
{
return singleTonObjPtr;
}
singleTon(const singleTon& singletonObj)
{
}
void operator =(const singleTon& singletonObj)
{
return;
}
private:
singleTon()
{
i = 50;
singleTonObjPtr = NULL;
}
~singleTon()
{
}
int i;
static singleTon* singleTonObjPtr;
};
singleTon* singleTon::singleTonObjPtr = NULL;
int _tmain(int argc, _TCHAR* argv[])
{
singleTon *singleTOnPtr =NULL;
singleTOnPtr = singleTon::InitInstance();
singleTon *singleTOnPtr2 = singleTOnPtr->getObject();
singleTon obj3 = *singleTon::InitInstance();
}
Upvotes: 0
Views: 152
Reputation: 254431
It might help if you read (and post) the compiler error. I get:
test.cpp:37: error: ‘singleTon::~singleTon()’ is private
test.cpp:55: error: within this context
where line 37 is the declaration of the private destructor, and line 55 is the point in _tmain
at which the code tries to create and destroy an object, requiring a public destructor.
If you want to be able to create and destroy multiple copies of your confusingly-named-not-quite-singleton-thingy, then you'll need to make the destructor public. For this simple example, you can do that by removing the destructor altogether; the implicit constructor will be public, and there are no members that need non-trivial destruction.
Upvotes: 1
Reputation: 227370
First of all, operator= is the assignment operator, so you are assigning, not copying. Your assignment operator returns void
, but it should return a singleTon&
. But you really have to ask what the meaning of assigning to a singleton is. For example:
singleTon a = singleTon::InitInstance(); // single instance
singleTon b = singleTon::InitInstance(); // same instance
a = b; // assignment, but a and b really are the same instance, so what's the point?
And, for a singleton, there should no default-construction:
singleTon b; // this should not be allowed
b = a; // so this makes no sense
Upvotes: 2