|
-
February 26th, 2006, 07:28 PM
#1
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 ?
-
February 26th, 2006, 07:39 PM
#2
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.
quoted from C++ Coding Standards:
KISS (Keep It Simple Software):
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
Avoid magic number:
Programming isn't magic, so don't incant it.
-
February 26th, 2006, 08:49 PM
#3
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+=
Last edited by laserlight; February 26th, 2006 at 08:51 PM.
-
February 27th, 2006, 01:17 AM
#4
Re: Overloading operator
Can you help me with my homework assignment?, Before you post!, Use code tags, How to post!, Codeguru technical FAQs, C++ FAQ Lite, Stroustrup: C++ Style and Technique FAQ, Guru of the Week, Comeau C and C++ FAQs, Comeau C++ Templates FAQs, CUJ @ DDJ, Spam threshold
My Blogs : Learning C++ is fun | Abnegator's reflections
Open Threads : C++ Aha! Moments | Nature of work in C++?
-
February 27th, 2006, 01:28 AM
#5
Re: Overloading operator
- Sreehari
"Sometimes I think the surest sign that intelligent life exists elsewhere in the universe is that none of it has tried to contact us."
" Everybody is sent to Earth on a purpose. I am so Lagging behind that i won't die." – Calvin
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|