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?

4
  • I don't understand what the - and the * have to do with each other. Commented Apr 10, 2013 at 18:17
  • Think of it as 0 - foo, not foo * -1. Commented Apr 10, 2013 at 18:17
  • @JamesMcLaughlin Ah, that made me understand what the asker meant. Commented Apr 10, 2013 at 18:18
  • 1
    Something like the question here? stackoverflow.com/questions/2155275/… Commented Apr 10, 2013 at 18:20

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

5 Comments

Wow, that was simple! I'll accept it once I can verify it works.
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.
@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.
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?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.