Much of the material in these notes is derived from the Hubbard book (see course outline).
Overloading Operators, the this Pointer, friend Functions
The C++ operators are defined to work on the fundamental types (e.g. + works on int, float, etc.). When you create a class you sometimes need to define operations for the class, and sometimes you would like to use the “standard” operators rather than, say, define an add(x, c) function. These operators may work slightly differently on the structured objects of the class than they do on data objects of the fundamental types. The nice thing about C++ (as opposed to, say, Pascal, COBOL, etc.) is that we can redefine the = or + operator to work on the new type that we create by defining a class.
The assignment operator is used to copy the value of one object to another. Just like the default constructor and copy constructor it is automatically overloaded for our new class even if we do not explicitly define it; However, just like the constructors we can explicitly define it if we wish. Ex.
Rational (int=0, int=1);
Rational (const Rational&);
Rational& operator=(const Rational&);
The function name for the assignment operator is “operator=”. So operator overloading is actually no different from function overloading.
Rational& operator= (const Rational&);
Return fn nametype of input
and in general, where T is a placeholder that stands for “any type,” the syntax is:
T& operator= (const T&);
overloading.doc1 of 14