Lecture Notes for Introduction to Computer Science II

7 June 2001 - Operator Overloading


  1. what are operators

    1. operators are functions - accept two arguments and return a value

    2. int plus(int, int) { . . .} - binary function

    3. int negative(int) { . . . } - unary function

  2. because operators are functions, they can be overloaded

    1. the syntax is a bit odd, requiring the keyword operator

    2. for example bool operator == (hand h1, hand h2) { . . . }

    3. the number of operators must match the standard use

      1. wrong - bool operator == (hand h1, hand h2, hand h3) { . . }

    4. the types of the arguments may be different, as can the return value

      1. example double operator == (hand h1, int i) { . . . }

      2. fooling with the return value is bad programming

    5. one of the argument types must be a class

      1. wrong - int operator / (int i, int j) { . . . }

    6. there's two ways to call operator functions

      1. the operator way - hand h1, h2; if (h1 == h2) { . . . }

      2. the function way - hand h1, h2; if (operator ==(h1, h2) { . . . }

    7. not all operators can be overloaded - the dot operator

  3. because they're functions, operators can be member functions

    1. the syntax is the same, except for the implicit argument

      1. for example - bool operator == (hand h) { . . . }

    2. the calling syntax is the same

      1. the operator way - hand h1, h2; if (h1 == h2) { . . . }

      2. the function way - hand h1, h2; if (h1.operator ==(h2) { . . . }

    3. operator overloading is sometimes handy, but

      1. used improperly it can make code difficult to understand

      2. it interacts in strange, subtle, and unfortunate ways with other c++ features

      3. defining overloaded operators correctly requires a lot of work


    This page last modified on 25 June 2001.