Binary Operator Overloading


So now you ask, what is this operator overloading stuff, how will it help me make the supreme burrito, and what the heck does "binary operator overloading" mean? Lets take this one step at a time. First, a quick example of operator overloading.

#include <iostream.h>

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

void main(void) {
  Burrito b1(5,10), b2(10,5), b3;
  b3 = b1 + b2;
}

Notice a couple things about the method which defines the "+" operator for the Burrito class:

  • The method is called from the class which precedes the operator, and the object which comes after the operator is sent as the parameter. In the above example, this means that the operator called is b1's "+" operator, and the parameter (newburrito) is b2.
  • The operator method can access private data members of the parameter which it is sent. (For example, newburrito.amtbeef and newburrito.amtbean in the code above)
  • The above is an example of a binary overloaded operator, because we are overloading an operator which has two operands, also known as a binary operator (as opposed to a unary operator with only one operand, like the postfix/prefix operators ++ and --).
  • The operand which is called is the one defined in the object before the operator, and the parameter is the object after the operator. For example, in the above code, the operator used is b1's "+" operator, and the parameter which it is sent (newburrito) is b2.

So now we can go use this class to make gratuitous use of the overloaded "+" operator in our pgram to find the supreme burrito, without having to type addburrito a lot. So we can program faster, and thus find the supreme burrito faster. A win-win situation!


Table of Contents

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