argument type of assignment operator (reference or value?)

510 views Asked by At

I have a class and want to overload the "+" and "=" operator for this class. so i implement operator+ as a friend function and operator= as a member funcion...

If the argument type of operator= defined as reference, then the following line can't be run because the right hand side is a value and don't have any address :

sum = A + B;   // sum, A and B are objects of my class

But i want to be able to do such assignments and also want to pass arguments to operator= by reference (because objects of my class are huge). is it possible or i have to pass arguments to operator= by value??

3

There are 3 answers

0
TartanLlama On BEST ANSWER

You just need to take in the argument by reference-to-const:

MyClass& operator= (const MyClass&);

const references can bind to rvalues, so sum = A + B is valid.

0
Peter On

A class' operator=() typically accepts a const reference. So X::operator() will accept a const X &. This does allow chaining. A non-const reference will not allow the results of expressions like A + B to be passed (since that logically requires a temporary).

operator=() for arguments of other type (e.g. lhs X and rhs Y) can be passed by value (if Y has working copy constructor) i.e. X &X::operator=(Y), but passing by const reference is more common in practice, simply because it reduces chances of creating temporaries.

2
psliwa On

Operator overloads are normal functions that are able to use references as arguments. Remember to take care of rvalues by using const references instead of clean ones because they prolong their lifes to your function's scope.

BTW, you don't necessary have to declare operator+ as a friend function - you can also make it a member of your class.

struct A
{
    int x;
    A(int x): x(x) {}
    A operator+(const A&);
    A& operator=(const A&);
};

A A::operator+(const A& right_side_of_equation)
{
    ...
}

A& A::operator=(const A& object_to_be_assigned)
{
    ...
}