Unary Operator Overloading


In the last section we breifly mentioned overloading unary operators, such as ++ and --. It really isn't too different from overloading a binary operator such as +. Here's a quick example which will incremenet the data in our burrito variable by one and return the new burrito.

class Burrito {
  private:
    int amtbeef, amtbean;
  public:
    Burrito(int newbeef, newbean) {
      amtbeef = newbeef;
      amtbean = newbean;
    }
    Burrito operator ++() {
      amtbeef++; amtbean++;
      return Burrito(amtbeef, amtbean);
    }
};

In the above example, we see many similarities to our previous example of a binary overloaded operator. In fact the only real difference is that there is no parameter passed to the operator method, which makes sense since we are only concerned with one operand, which is the object whose operator is being used.

However, there is one small caveat that you must keep in mind specifically when overloading the ++ and -- operators. As you saw earlier, the statement b = ++a; does something slightly different from b = a++; if both a and b are ints. The first is the same as a = a + 1; b = a; , the second is the same as b = a; a = a + 1; . However, when overloading the ++ (or --) operator, you cannot make any distinction between whether the operator was used as a++ or ++a if a is a Burrito (or some other user-defined type). Both uses of the operator have the same effect.


Table of Contents

Operator Overloading | Binary Operator Overloading | Unary Operator Overloading | Overloading Conversion Operators
Using Overloaded Operators | Exercises | Continuing the Journey