84

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.

nos
  • 215,098
  • 54
  • 400
  • 488
Ilya Suzdalnitski
  • 51,312
  • 50
  • 131
  • 167
  • 7
    Style comment: don't prefix your variables with '_'. This style is reserved for the implementation (compiler) and you may have conflicts. Also, readers my unintentionally recognize your variables as implementation variables because of the '_' prefix. You don't need to use '_' inside functions; they will be readable without it. – Thomas Matthews Jan 28 '10 at 18:48
  • 4
    Two underscores are reserved for implementation, not just one. – el.pescado - нет войне Jul 07 '10 at 11:56
  • I believe that it's _MACROs and __identifiers. – Puppy Jul 07 '10 at 12:20
  • 2
    Please tell me why you are using `.getX()` and `.getY()` on your simple Vector type – bobobobo May 09 '13 at 01:00
  • 1
    To be [precise](https://en.cppreference.com/w/cpp/language/identifiers): Identifiers with two subsequent underscores *anywhere* are reserved – *always*, identifiers starting with an underscore followed by a captital letter are *always* reserved, too, any identifier starting with an underscore is reserved *at global namespace*. – Aconcagua Jun 28 '19 at 08:05

2 Answers2

139

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;
   }
};
  • 8
    @Kornel Kisielewicz: Calling it "the *only* right solution" is misleading. Unary `-` can be overloaded by a standalone function as well, which would closely mirror the OP's implementation of `oppositeVector`. – AnT Nov 29 '12 at 19:00
32

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.

kennytm
  • 491,404
  • 99
  • 1,053
  • 989
Alexander Gessler
  • 44,353
  • 6
  • 80
  • 121