Overloaded assignment operator is not getting called
I have written a overloaded assignment operator of class perform
copying all the variable values.
For ex :in Exp.cpp
开发者_运维知识库class perform
{
LOG *ptr;
int a;
//constructor
//destructor
perform operator=(const perform & rhs){
ptr = rhs.ptr; a=rhs.s;
return * this;}
};
In another class output
, I have declared a pointer for abc
.
perform * ptr = StatCol::CreateCol(frm);
abc = ptr; //this line should invoke assignment overloaded.
//but in my case it's not invoked.
Assuming abc is a Perform object, you need to dereference the pointer you are assigning:
abc = * ptr;
If abc itself is a pointer, then you can't do what you are asking - you can't overload assignment where the LHS is a pointer. You would have to dereference both pointers:
* abc = * ptr;
Also, it is safer to return via reference thus avoiding a copy constructor being invoked.
const perform& operator=(const perform & rhs){
if (this != &rhs)
{
ptr = rhs.ptr; a=rhs.s;
}
return * this;
}
Custom assignment operator works only with user defined types so do like this:
perform p1,p2;
p1 = p2;
perform *p = &p2;
p1 = *p;
You can't override assignment of built in types(int , char etc.).
perform *p1,*p2;
p1 = p2;
It simply copies the address of p2 to p1.
In the sample code you are assigning pointers, so there is no chance you could ever call the assignment operator without dereferencing the pointer.
And using this design, the risk of doing shallow copy is huge. In addition the C++ assignment operator signature is: 'perform & operator = ( ... )' as stated in the standard. It must return a reference to the same object in order for the compiler to consider it as you expect.
more about assignment operator....
精彩评论