Operator overloading problem

Hello,

I am trying to overload unary - operator and landed in the following scenarios.

case I :
if I write something like this, then the call goes into infinite loop
1
2
3
4
const Interger Interger::operator-(){
     cout << "Interger::-operator --> postfix" << endl;
     return Interger(-(*this));
}


case II:
if the same thing I do using friend
1
2
3
4
const Interger operator-(const Interger& rv) {
   cout << "Interger::-operator --> postfix" << endl;
   return Interger(-rv.i);
}

then it works perfectly fine. Does anyone knows about it.
In your non-friend form:

return Interger(-(*this));

You are doing the - on *this.. which calls the overloaded - operator (so it's basically calling itself).

Whereas in your friend form:

return Interger(-rv.i);

You are not doing the - on rv (which would cause the same infinite loop problem), but instead are doing it on i, which is correct.


So to recap:

1
2
3
4
5
6
7
// BAD (infinite loop):
return Interger(-(*this));  // <- non-friend
return Interger(-rv);  // <- friend

// GOOD:
return Interger( -i );  // <- non-friend
return Interger( -rv.i );  // <- friend 



Also, it's spelled "Integer", not "Interger"
Topic archived. No new replies allowed.