Problem with operator overload

A Position class is a class with x,y variables. I'm getting bad values of y when I try to add them together. If someone could point out a mistake, that would help :)

position.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Position::Position(const Position& other)
  :x(other.x), y(other.y)
{}

Position& Position::operator+(const Position& other){
  return Position(*this) += other;
}
Position& Position::operator+=(const Position& other){
  this->x += other.x;
  this->y += other.y;
  return *this;
}
void Position::print(void) const{
  std::cout << "Pos: (" << this->x << ", " << this->y << ")\n";
}


main.cpp
1
2
3
4
5
Position first(1,1);
Position second(2,3);
(first + second).print();  // Prints garbage for y 
Position third(first + second);
third.print(); // prints the correct value 


Any thoughts?
1
2
3
Position& Position::operator+(const Position& other){
  return Position(*this) += other;
}


This returns a reference to a variable that goes out of scope as soon as the function returns.

Remove the ampersand from the return type.
Thanks. Interesting that doesn't cause a warning, this does:
1
2
3
4
5
Position& Position::operator+(const Position& other){
  Position newPos = *this;
  newPos += other;
  return newPos;
}
In the original you were returning a reference to the return value from operator+=, and that return value was a reference. The compiler can't, without analyzing operator+=, assume that operator += returns a reference to the same object it was invoked on, so it doesn't warn you. Depending on the implementation of operator+=, it could be perfectly safe to do.

In the second, the compiler can clearly see you're returning a reference to a local object.
Last edited on
Topic archived. No new replies allowed.