How to overload unary minus operator in C++?

C++Operator Overloading

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

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;
   }
};

Solution 2 - C++

It's

Vector2f operator-(const Vector2f& in) {
   return Vector2f(-in.x,-in.y);
}

Can be within the class, or outside. My sample is in namespace scope.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIlya SuzdalnitskiView Question on Stackoverflow
Solution 1 - C++anonView Answer on Stackoverflow
Solution 2 - C++Alexander GesslerView Answer on Stackoverflow