views:

97

answers:

4

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 assigment overloaded.
           //but in my case it's not invoked.

please please.help

+6  A: 

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;
anon
yes,you are rite, abc is a pointer .
Vishu
in this case what to do?
Vishu
@Vishu Do what I said - dereference both pointers - this will use your assignment operator.
anon
Please tell how?am not getting.what i want finnaly is abc(pointer of type Perform) should contained copied values.And it has to be pointer only.i canot change.In this case how do i ensure my asigment operator is called
Vishu
@Vishnu I've told you what to do - I don't see I can be any clearer.
anon
Ok,LHS should not be pointer,then only my asigment operator is called is it?Thanks lot.will try and comment.thanks
Vishu
performSorry this is actual line,i missed the referance symbol in the above .In this case LHS can be pointer?Sorry if am wrong.
Vishu
@Vishu You are wrong. The C++ language simply does not allow operator=() to be overloaded for assignment to pointers.
anon
Thanks a lot.its working now.And thanks for the knowledge sharing
Vishu
A: 

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;
   }
yes i have written the same as aobve. But its not getting called.LHS is a pointer.i.e abc is a pointer
Vishu
A: 
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.
Ashish
A: 

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....

Gold
The standard has no requirement on the return type, which never takes part in overloading.
anon