warning: reference to local variable ‘tmp’ returned

Title says all. It happens when overloading the operator-.

1
2
3
4
5
6
7
8
const ColeccionCoches &ColeccionCoches::operator -(const char *fichero) const { 
ColeccionCoches tmp;
.
.
//irrelevant code here...
.
.
return tmp;


I am pretty sure this must be done in order to chaining "-" operators (tmp-tmp2-tmp3).
you're returning a reference to a local variable, that's your problem, when the function returns 'tmp' goes out of scope and so the reference is to what? An object that no longer exists.
Indeed, the problem is that I've seen doing it that way (creating a temporary object and then returning it) with no problems whatsoever. So this can be done, somehow, but I don't know how, lol.

for example:

1
2
3
4
5
6
Polinomio operator* (const float c, const Polinomio& p){
Polinomio tmp (p.MaxGrado);
for (int i=0; i<= tmp.MaxGrado; i++)
  tmp.Coef[i] = c * p.Coef[i];
  return (tmp);
}


returns a reference toa local variable but does works, why?
Last edited on
it returns a Polinomio object, the object itself, not a reference to the object, that's the difference.

EDIT - well more precisely it makes a copy of the object to return
Last edited on
Oh, I think I get what you mean:

const ColeccionCoches ColeccionCoches::operator -(const char *fichero) const {

Changed it to that and it works. Putting the & makes it to return a reference, and if you dont put it, it will return the object itself, right?

thanks! No warnings now ;)
If you want to return a tmp object then you must return by value, not by reference:
1
2
3
4
5
6
7
8
9
10
const ColeccionCoches ColeccionCoches::operator -(const char *fichero) const 
{ 
    ColeccionCoches tmp;
    .
    .
    //irrelevant code here...
    .
    .
    return tmp;
}

Also you might find this reference on operator overloading useful:
http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Arithmetic_operators
Topic archived. No new replies allowed.