0

Say I have an int, like this:

int foo = 5;

I could then do this:

int bar = -foo;     // -5

I want to be able to do the same with my class, so how do I overload the - operator, used as * -1? Do I have to overload the * operator to do so?

MiJyn
  • 5,327
  • 4
  • 37
  • 64

1 Answers1

4
class MyClass
{
    friend MyClass operator-(const MyClass& x);
};

or

class MyClass
{
    MyClass operator-() const;
};

Take your pick (although I would go for the first).

john
  • 85,011
  • 4
  • 57
  • 81
  • Wow, that was simple! I'll accept it once I can verify it works. – MiJyn Apr 10 '13 at 18:19
  • 2
    I'd go for the second, unless the `-` operator didn't need access to `protected` or `private` parts of `MyClass`, in which case I'd go for neither and just write `MyClass operator-(const MyClass& x);`. I prefer to avoid `friend` if at all possible. – Mike DeSimone Apr 10 '13 at 18:21
  • 1
    @MikeDeSimone A global non-friend function is certainly the best if possible. I put friend there just to emphasize that this option does not involve a member function. – john Apr 10 '13 at 18:22
  • Why is a global non-friend function or friend function better than a member function? A member function means the declaration is in a place everyone is looking for functionality of the class. It's also logically a function of the class. What benefit is there? – David Apr 10 '13 at 18:26
  • 1
    @Dave There a real problem with member functions for symmetric binary operators (like +, *, < etc) in that the rules of C++ are such that different conversion rules apply to the left and right hand sides of your operator. This isn't a problem for operators which modify an existing object rather than return a new one (like +=). Unary - is somewhere in between, but since it creates a new object rather than modifies an existing one then stylistically I group it with binary +, - etc. – john Apr 10 '13 at 18:33