Lecture Notes for Advanced Programming II

10 April 2001 - Operator Overloading


  1. what is operator overloading

    1. redefine the behavior of existing c++ operators, including the ,, ->, [], new, delete and cast operators

  2. what can't you do

    1. overload the ., .*, ->*, ?:, ::, and sizeof() operators

    2. change an operator's arity, presidence, and associativity

    3. overload operators for predefined-type values

  3. it is sometimes useful to remember that a op b is equivalent to a.op(b)

  4. overloading and member functions

    1. the left operand for overloaded member operators is implicitly defined by the this argument, no need to give it

    2. this causes problems - commutativity; complex(1, 2) + 3 vs. 3 + complex(1, 2)

    3. how to fix

      1. can't make another overloaded member operator - left argument will be the same

      2. an external function can't get inside the class operator

      3. an external friend function does the trick

    4. example - overloading the stream operators << and >>

      1. overloading these operators is nifty - compact io notation; non commutative

      2. how - << (for example) can't be a member function - wrong left argument type

      3. external function can't get access to class internals

      4. friend external function

  5. other overloading oddities

    1. distinguishing between pre- and post-fix -- and ++ - the magic argument for postfix

    2. defining op and = doesn't define op=

    3. overloading cast operators

  6. operator overloading

    1. sometime's it's useful - overloading the stream operators, array access, arrow operator

    2. sometime's it's a pain - non-commutative operations, interactions with other features, understanding other's overloaded operators

    3. operator overloading interacts badly with a large range of other c++ features - worse than templates

  7. rules for overloading

    1. don't get clever

      1. natural, consistent meanings

        1. + means add, not subtract

        2. ^ has low presidence, exponentiation has high presidence

        3. providing consistent meanings can be a pain - commutativity; making sure a < b is identical to b > a or !(a >= b)

    2. provide complete sets of overloaded operators - op, =, and op=

  8. example - overloading array access

    1. arrays are easier to overload - not comutative, no relations

    2. distinguishing left and right uses of arrays

    3. allowing multiple uses of an array in an expression

  9. example - overloading stream access operators

    1. even simpler than arrays - no left-right distinction


This page last modified on 13 April 2001.