Click to See Complete Forum and Search --> : Overloading operator
GoDaddy
February 26th, 2006, 06:28 PM
Is it better to return a reference or a new instance of the object?
For example :
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 ?
Kheun
February 26th, 2006, 06:39 PM
You should use the second one for this case. This is because operator+ should not have any side effect on it's operands.
laserlight
February 26th, 2006, 07:49 PM
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+=
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+=
exterminator
February 27th, 2006, 12:17 AM
Here is the link to it - Overloading an operator... I'm really not getting it (http://www.codeguru.com/forum/showthread.php?t=373719&page=1&pp=15&highlight=RVO). ;) Regards.
sreehari
February 27th, 2006, 12:28 AM
Operator Overloading FAQ (http://www.parashift.com/c++-faq-lite/operator-overloading.html)
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.