How to overload unary minus operator in C++?

Ilya Suzdalnitski picture Ilya Suzdalnitski · Jan 28, 2010 · Viewed 57.6k times · Source

I'm implementing vector class and I need to get an opposite of some vector. Is it possible to define this method using operator overloading?

Here's what I mean:

Vector2f vector1 = -vector2;

Here's what I want this operator to accomplish:

Vector2f& oppositeVector(const Vector2f &_vector)
{
 x = -_vector.getX();
 y = -_vector.getY();

 return *this;
}

Thanks.

Answer

anon picture anon · Jan 28, 2010

Yes, but you don't provide it with a parameter:

class Vector {
   ...
   Vector operator-()  {
     // your code here
   }
};

Note that you should not return *this. The unary - operator needs to create a brand new Vector value, not change the thing it is applied to, so your code may want to look something like this:

class Vector {
   ...
   Vector operator-() const {
      Vector v;
      v.x = -x;
      v.y = -y;
      return v;
   }
};