-
Which is better?
I was wondering which way to overload operators would be better. Pretend that Example is a class with one integer member x, and a constructor that takes one int and sets x to it.
Example 1:
Code:
const Example operator+(const Example &e) const {
return Example(x + e.x);
}
Example &operator+=(const Example &e) {
x += e.x;
return *this;
}
Example 2:
Code:
const Example operator+(const Example &e) const {
return Example(x + e.x);
}
Example &operator+=(const Example &e) {
*this = *this + e;
return *this;
}
Is either way better than the other, or are they similar in terms of good practice, polymorphity (is that a word :D ?), and speed? Thanks :D !
-
neither. operator + should not be a member. now work out why!
-
I canīt figure it out why. Could you, please, give just a tip? I think that it is because + is a binary operator. Am I correct?
-
Aside form Stoned_Coder's point, there is a good reason not to implement one operator in terms of another... especially the way you have it: efficiency.
Think about how many function/operator calls you have in each of the two examples, and think of the assignments being made. Assigning an int is relatively cheap, but assignment of object's isn't.
Your first example just has addition and assignment of operations for a primitive type (int).
Your second example, however, would be significantly more complicated. You call the 'operator+' for your class, and then call 'operator='. With just an int member, it'll be a good deal slower because of the function calls. If the class is complex, however, and 'operator=' does a lot, then it could get very slow.
-
-
answer this question and you get your answer. If operator + is a member then what will happen in 1 and what will happen in 2 and what would have happened had operator + been a non-member.
1) obj = anotherobj + 1;
2) obj = 1 + anotherobj;