Overloading Unary Operators
A unary operator works with one operand.
Examples:
++xx++--x-x!x
When a unary operator is overloaded as a member function, it usually takes no explicit parameter because the object itself is the operand.
++counter;
is like:
counter.operator++();
Prefix and Postfix Difference
C++ uses different signatures for prefix and postfix increment.
Prefix:
Counter& operator++();
Postfix:
Counter operator++(int);
The int parameter in postfix is a dummy parameter. You do not normally use it. It only helps the compiler distinguish x++ from ++x.
Complete Example
#include <iostream>
using namespace std;
class Counter {
private:
int value;
public:
Counter(int v = 0) : value(v) {}
Counter& operator++() {
++value;
return *this;
}
Counter operator++(int) {
Counter oldValue = *this;
++value;
return oldValue;
}
Counter operator-() const {
return Counter(-value);
}
void display() const {
cout << value << endl;
}
};
int main() {
Counter c(5);
++c;
c.display();
Counter old = c++;
old.display();
c.display();
Counter negative = -c;
negative.display();
return 0;
}
Output:
6
6
7
-7
Why Prefix Returns Reference
Prefix ++x changes the object first and returns the updated object. Returning by reference avoids an unnecessary copy and supports chaining.
++(++c);
Why Postfix Returns Old Copy
Postfix x++ must return the old value, then change the object. That is why it stores a copy before incrementing.
Counter old = c++;
old gets the previous value.
Viva Answer
Unary operator overloading defines operator behavior for one object. For member unary overloads, no explicit operand parameter is needed because the calling object is the operand. Prefix ++ uses operator++(), while postfix ++ uses operator++(int) with a dummy integer parameter.
Quick Check
- Why does member unary
operator-()need no parameter? - What is the dummy
intused for in postfix++? - Which one usually returns a reference: prefix or postfix?