Two + operators

• 10-29-2003
shane1985
Two + operators
Okay, I'm writing a class, and I want to know how I can have two different + operators in the class.

Is it even possible to do this?

Thanks!
• 10-29-2003
Cat
Yes, for different types of right-hand side arguments.
• 10-29-2003
shane1985
So as long as they have different parameters, you can do it?
• 10-29-2003
joshdick
Isn't there also a uranary + operator analgalous to the uranary - operator? I could be very wrong about this...
• 10-29-2003
Cat
++ and -- you mean?
• 10-29-2003
Zach L.
"unary" ;)

You mean a '+5' analogous to '-5' (for example)?
• 10-29-2003
joshdick
Yeah, Zach knows what I'm thinking. Is that possible?
• 10-29-2003
Zach L.
Yep.

Code:

```class A { public:   A operator+(); // Unary +: A x; +x;   A operator+(A b); // Binary +: A x, y; x + y; };```
• 10-29-2003
joshdick
*fist pump*
And I suppose other things would go on this line...
• 10-30-2003
pianorain
Quote:

Originally posted by Zach L.
Yep.

Code:

```class A { public:   A operator+(); // Unary +: A x; +x;   A operator+(A b); // Binary +: A x, y; x + y; };```

Not that I don't have confidence in you, Zach, but I was almost sure that you were wrong. Then I checked and learned.

Why is there a unary + operator? With the basic types, +x returns x. So why use +x at all?
• 10-30-2003
glUser3f
+x = x if x is a number, however, c++ provides a way to overload + so you can use it to do whatever you want for your class, one of the features that I like in c++.
• 10-30-2003
Zach L.
Quote:

Originally posted by pianorain
Not that I don't have confidence in you, Zach, but I was almost sure that you were wrong. Then I checked and learned.

Thats good. Someone keeping me honest. :)

Quote:

Why is there a unary + operator? With the basic types, +x returns x. So why use +x at all?

I really can't see much use for it. If you're gonna use operators, they should logically work as you'd expect them (otherwise, use a named function), and I can't think of any logical place where +x != x. It was probably added to C++ since it is mathematically valid syntax.