0

I'm trying to define "-=" and "-" for a class that represents vector in 2D but I get this error:

Vecteur2D.cc:131:7: error: no viable overloaded '-=' vec1-=vec2;

Vecteur2D.cc:81:23: note: candidate function not viable: 'this' argument has
    type 'const Vecteur2D', but method is not marked const
Vecteur2D& Vecteur2D::operator -= (const Vecteur2D& vec){


here is my code for the two operator: 

Vecteur2D& Vecteur2D::operator -= (const Vecteur2D& vec){
  x_=x_-vec.x_;
  y_=y_-vec.y_;
  return *this;
  }

and: 


const Vecteur2D operator +(const Vecteur2D& vec1, const Vecteur2D& vec2){
vec1+=vec2;
return vec1;
}


ml64
  • 3
  • 1

1 Answers1

1

You cannot call a non-const method on a const instance. Your operator-= looks ok, but if you try to call it eg like this:

const Vecteur2D x,y;
x -= y;               // error

You get an error similar to the one you report. -= is expected to modify the left operand and your operator-= does that. The left operand cannot be const.

Your operator+= has issues with const correctness as well:

const Vecteur2D operator +(const Vecteur2D& vec1, const Vecteur2D& vec2){
vec1+=vec2;
return vec1;
}

You cannot modify vec1 because it is const. operator+ is expected to not modify its operands and return a new instance. Your operator+ is not doing that. Assuming you have a correct += the operator+ can be written as:

Vecteur2D operator +(const Vecteur2D& vec1, const Vecteur2D& vec2){
    Vecteur2D result = vec1;  // non const copy
    result += vec2;
    return result;
}

For more details I refer you to What are the basic rules and idioms for operator overloading?

(PS: As far as I know, previously it was considered good practice to return const values, though it prevents move semantics and is no longer recommended)

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • 1
    Another way to get a copy to do `+=` on and return is to make the first argument a plain `Vecteur2D` without const or reference and then use it for the add-assign and return value. – Zan Lynx Mar 20 '21 at 15:16