Lecture Notes for Advanced Programming II
10 April 2001 - Operator Overloading
- what is operator overloading
- redefine the behavior of existing c++ operators, including the
,
, ->
, []
, new
, delete
and cast operators
- what can't you do
- overload the
.
, .*
, ->*
, ?:
, ::
, and
sizeof()
operators
- change an operator's arity, presidence, and associativity
- overload operators for predefined-type values
- it is sometimes useful to remember that
a
op b
is
equivalent to a.
op(b)
- overloading and member functions
- the left operand for overloaded member operators is implicitly defined
by the
this
argument, no need to give it
- this causes problems - commutativity;
complex(1, 2) + 3
vs.
3 + complex(1, 2)
- how to fix
- can't make another overloaded member operator - left argument will be
the same
- an external function can't get inside the class operator
- an external friend function does the trick
- example - overloading the stream operators
<<
and >>
- overloading these operators is nifty - compact io notation; non
commutative
- how -
<<
(for example) can't be a member function - wrong left
argument type
- external function can't get access to class internals
- friend external function
- other overloading oddities
- distinguishing between pre- and post-fix
--
and ++
- the
magic argument for postfix
- defining op and
=
doesn't define op=
- overloading cast operators
- operator overloading
- sometime's it's useful - overloading the stream operators, array
access, arrow operator
- sometime's it's a pain - non-commutative operations, interactions with
other features, understanding other's overloaded operators
- operator overloading interacts badly with a large range of other
c++ features - worse than templates
- rules for overloading
- don't get clever
- natural, consistent meanings
-
+
means add, not subtract
-
^
has low presidence, exponentiation has high presidence
- providing consistent meanings can be a pain - commutativity; making
sure
a < b
is identical to b > a
or !(a >= b)
- provide complete sets of overloaded operators - op,
=
,
and op=
- example - overloading array access
- arrays are easier to overload - not comutative, no relations
- distinguishing left and right uses of arrays
- allowing multiple uses of an array in an expression
- example - overloading stream access operators
- even simpler than arrays - no left-right distinction
This page last modified on 13 April 2001.