-
Overloading operator
Is it better to return a reference or a new instance of the object?
For example :
Code:
class A
{
private :
int seed;
A(int s):seed(s){};
A& operator + (const A &a);
{
seed+=a.seed;
return *this;
}
A operator + (const A &a);
{
return A(seed+a.seed);
}
Which one is better ?
-
Re: Overloading operator
You should use the second one for this case. This is because operator+ should not have any side effect on it's operands.
-
Re: Overloading operator
One of my first few discussions here was about overloading arithmetic operators :)
The answer I eventually settled on was:
Declare operator+= as a member function taking an object passed by const reference, returning by reference.
Declare operator+ as a global function taking two objects passed by const reference, returning by value.
Implement operator+ in terms of operator+=
Code:
A& A::operator+=(const A& rhs) {
seed += rhs.seed;
return *this;
}
A operator+(const A& lhs, const A& rhs) {
return A(lhs) += rhs;
}
The idea is to keep to the same semantics as the native operator+ and operator+=
-
Re: Overloading operator
-
Re: Overloading operator