Chapter 8 - Operator Overloading: 2003 Prentice Hall, Inc. All Rights Reserved
Chapter 8 - Operator Overloading: 2003 Prentice Hall, Inc. All Rights Reserved
8.1 Introduction
• Types
– Built in (int, char) or user-defined
– Can use existing operators with user-defined types
• Cannot create new operators
• Overloading operators
– Create a function for the class
– Name function operator followed by symbol
• Operator+ for the addition operator +
• Cannot change
– How operators act on built-in data types
• I.e., cannot change integer addition
– Precedence of operator (order of evaluation)
• Use parentheses to force order-of-operations
– Associativity (left-to-right or right-to-left)
– Number of operands
• & is unitary, only acts on one operand
• Cannot create new operators
• Operators must be overloaded explicitly
– Overloading + does not overload +=
• Upcoming example
– If non-member function, needs two arguments
– Example:
class String {
friend const String &operator+=(
String &, const String & );
...
};
– y += z equivalent to operator+=( y, z )
• Arrays in C++
– No range checking
– Cannot be compared meaningfully with ==
– No array assignment (array names const pointers)
– Cannot input/output entire arrays at once
• One element at a time
• Example:Implement an Array class with
– Range checking
– Array assignment
– Arrays that know their size
– Outputting/inputting entire arrays with << and >>
– Array comparisons with == and !=
• Copy constructor
– Used whenever copy of object needed
• Passing by value (return value or parameter)
• Initializing an object with a copy of another
– Array newArray( oldArray );
– newArray copy of oldArray
– Prototype for class Array
• Array( const Array & );
• Must take reference
– Otherwise, pass by value
– Tries to make copy by calling copy constructor…
– Infinite loop
• Casting
– Traditionally, cast integers to floats, etc.
– May need to convert between user-defined types
• Cast operator (conversion operator)
– Convert from
• One class to another
• Class to built-in type (int, char, etc.)
– Must be non-static member function
• Cannot be friend
– Do not specify return type
• Implicitly returns type to which you are converting
• Example
– Prototype
A::operator char *() const;
• Casts class A to a temporary char *
• (char *)s calls s.operator char*()
– Also
• A::operator int() const;
• A::operator OtherClass() const;
• Return values
– Preincrement
• Returns by reference (Date &)
• lvalue (can be assigned)
– Postincrement
• Returns by value
• Returns temporary object with old value
• rvalue (cannot be on left side of assignment)
• Decrement operator analogous
fig08_12.cpp
d2 += 7 is January 3, 1993
output (1 of 1)
d3 is February 28, 1992
++d3 is February 29, 1992