CIS 250 - Operator overloading

Objectives

Overloading operators

A few restrictions on operator overloading should be mentioned before we move on:

Operators can be overloaded in C++. One of the most common operators to overload is the assignment operator (=). This is especially important if your object uses dynamically allocated memory.

It is considered very poor practice to overload an operator to make it do something unexpected, such as multiply by three for the increment operator.

Example of overloaded assignment operator prototype:
person2& operator=(const person2& p);
The argument being received is a reference to the object on the right side of the assignment operator. The code that will be running is within the object on the left side of the operator. Private variables from the other object are visible since both objects are of the same class. It is considered good practice to return a reference to the current object so assignment operations can be chained (eg. a = b = c = d;).

Example of overloaded equality operator prototype:
bool operator==(const person2& p) const;
The argument being received is a reference to the object on the right side of the equality operator. The code that will be running is within the object on the left side of the operator. Private variables from the other object are visible since both objects are of the same class.

We will create a demonstration program in class that illustrates how operators can be overloaded. The code will be posted to this website after we create it in class. The class we will be implementing involves complex numbers. If you are interested in reviewing what complex numbers are, there is a nice article on complex numbers on Wikipedia at http://en.wikipedia.org/wiki/Complex_number.

Demonstration of operator overloading: