20-CS-122-001 Computer Science II Spring 2012
Operator Overloading

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Prev      Next      Lectures

Operator overloading functions can be defined as members of a class or in file scope (at the top level)

   Example (member):

       class Fraction {
          long num;
          long denom;

        public:
          ...
          Fraction & operator +=(const Fraction &);
          ...
       };

       Fraction & Fraction::operator +=(Fraction & frac) {
          *this = *this + frac;
          return *this;
       }

          Equivalence: f1 += f2 <==> f1.operator+=(f2)

   Example (non-member):

       Fraction & operator +=(Fraction & f1, Fraction & f2){
          f1 = f1 + f2;
          return f1;
       }

          Equivalence: f1 += f2 <==> operator+=(f1,f2)

Non-member overloading may be the only option in some cases:

   Overload * :

       Fraction operator*(int i, Fraction & frac) {
          return Fraction(frac.num*i, frac.denom*i);
       }

   But

       Fraction operator*(Fraction & frac, int i)
   can be overloaded both ways.