overloading operator puzzle: return *this, or temporary variable?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class="centertext"> class Integer { int i; public: Integer(int ii) : i(ii) {} Integer operator+(const Integer& rv) const { // version 1 return Integer(i + rv.i); } Integer operator+(const Integer& rv) const { // version 2 Integer T; T.i += rv.i; return T; } Integer operator+(const & rv) { // version 2 i += rv.i; //thanks user vlad from moscow, you're right return *this; } };


here's my question:
1)version 1 and version 2 and version 3 which one is better?
2)is version 1 and 2 are same?
3)for version 3, return reference is better or than value ? how efficiency reference can improve?

4) why overloading = have to return by reference?
Last edited on
When overloading, the arguments have to differ in the combination of type & number of arguments, this how the compiler decide which one to use. All of your args are the same, That is a compiler error.
Among the overloaded operators the third one is the worst. It has a side effect that the original value of Integer is changed. For example, consider the followng code

1
2
3
4
Integer x( 10 ), y( 20 );
Integer z( 0 );

z = x + y;



It is natural to think that neither x nor y will be changed in the last statement. Consider an equivalent code where Integer is changed to fundamental type int

1
2
3
4
int x = 10, y = 20;
int z = 0;

z = x + y;


You will not assume that after the statement the value of x will be equal to 30, will you?

So in my opinion the best realization is the first one. It allows the compiler to apply optimization of the return value.

As for you last question then the following code is valid for fundamental types

1
2
3
int x;
( x = 10 ) += 10;
std::cout << "x = " << x << std::endl;


So user defined types shall follow the same convention.

EDIT: I am sorry. I thought that in the third operator there is expression

i += rv.i;

Instead you use

i + rv.i;


So the third operator is simply invalid because it does not do what is awaiting from it.

I suppose you meant i += rv.i that is it was a typo.
Last edited on
i += rv.i; //thanks user vlad from moscow, you're right

why version 2 is better than version 1?

I'm sorry, I don't digest this:
1
2
3
int x;
( x = 10 ) += 10;
std::cout << "x = " << x << std::endl;

why return by value can't do the ( x = 10 ) += 10;
Last edited on

TheIDeasMan wrote:
When overloading, the arguments have to differ in the combination of type & number of arguments, this how the compiler decide which one to use. All of your args are the same, That is a compiler error.


Can some one explain to me, for my education, why my comment was possibly wrong?

No one has posted anything to say it was wrong, but other replies imply that it is.
Topic archived. No new replies allowed.