Operator Overloading
Objective #1: Overload operators.
- Operator overloading allows a programmer to use a standard C++ operator (eg. *, +, -, etc.) in a different way than it is originally defined. You must provide instructions in the class definition so that C++ knows exactly how to handle the overloaded operator in this new situation. Operators that are overloaded within the class definition are considered to be members of that class (just like member functions).
- The prototype const string & operator = ( const string & str ); overloads the assignment operator (=) so that a programmer can write statements like myName = yourName; where myName and yourName are string objects. Otherwise this assignment would be illegal since the assignment operator (=) is conventionally only defined and expected to be used with normal data types like int, float, char, etc.
For example, the
assignment operator ( = ) is overloaded within the string class so that
the statements,
myString = yourString;
and
myName = "John";
are valid. This allows a programmer to use the assignment operator in contexts
that seem reasonable with string objects. Note that the assignment operator
cannot be used to assign one character array to another. Rather the
strcpy function must be used.
- The overloaded bracket operator
is used as the subscript operator ( [ ] ) in the string class
to allow a programmer to reference individual characters within a string.
Bounds-checking is performed within this method so that a "nice"
run-time error message appears when a programmer attempts to access and modify
an out-of-range index position of an string. Note that neither built-in
C++ character arrays nor strings from the C++ string class perform this kind
of bounds-checking. The authors of the string class added this feature to
make it easier to work with strings.
- Overloading <<
and >> allows the programmer to use the insertion (i.e. output) and
extraction (i.e. input) operators with strings. Otherwise the statement,
cout << myName;
would not be legal if myName were an string object.