Vishu
Vishu

Reputation: 89

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.

Upvotes: 1

Views: 2362

Answers (4)

Gold
Gold

Reputation: 1

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

Upvotes: 0

Ashish
Ashish

Reputation: 8529

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.

Upvotes: 0

nsivakr
nsivakr

Reputation: 1595

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;
   }

Upvotes: 0

anon
anon

Reputation:

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;

Upvotes: 10

Related Questions