-1

While reading this article it seems that the operator + is unary. How is that. From my understanding a unary operator is an operator that does not depend on another variable for its operation like ++a or a-- . How is the variable '+' unary. I thought it was binary ? I would appreciate it if some one could clear this up.

MistyD
  • 16,373
  • 40
  • 138
  • 240
  • 2
    There's a unary plus (`+x`) and a binary plus (`a + b`). He must be referring to only one. – David G Nov 09 '14 at 00:12
  • By unary, they mean that it can be used for indicating the sign . As in `(-) for negative` and `(+) for positive` – saruftw Nov 09 '14 at 00:13

2 Answers2

6

+ is both a unary and binary operator. The unary + form (+a) forces the operand to be evaluated as a number or a pointer, while the binary form + form (a + b) is addition.

Unary + is generally the opposite of unary -; applying it to any numeric value will not change it. (+1 == 1) However, it does have some uses, including forcing an array to decay into a pointer:

template <typename T> void foo(const T &) { }

void test() {
    int a[10];

    foo(a);  // Calls foo<int[10]>()
    foo(+a); // Calls foo<int*>()
}

(Demo)

It's the same deal with the - and * operators. You have -a (negation) and a - b (subtraction); *a (pointer dereference) and a * b (multiplication).

You overload both versions differently. For overloading via member functions:

public:
    T operator+() const;          // Unary
    T operator+(const U &) const; // Binary

As with any other operator overload, both forms can return a value different from their enclosing type; for example you might have a string class whose operator+() returns a numeric type. This would be in line with the convention of unary + evaluating its operand as a number.

You can overload these operators as free functions, too:

T operator+(const U &);            // Unary, called on type U and returns T.
T operator+(const U &, const V &); // Binary, called on types U and V and returns T.
cdhowie
  • 158,093
  • 24
  • 286
  • 300
1

Unary + as in +a is defined to complement unary - (-a). It is the "default" so actually not often if ever used. However it can be used with variables refering to classes, where it can be overloaded to have a class-specific meaning. So it is not quite entirely useless.

davidc
  • 132
  • 1
  • 4