Operator overloading

Objectives

  • Write code to overload operators
  • Implement a class for complex numbers

Overloading operators

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

  • You can't create new operators
  • You can't change the number of arguments an operator takes
  • You can't change operator precedence
  • You can't change operator associativity
  • You can't use default arguments when you overload operators
  • You can't change the way operators work on the built-in data types
  • You can't overload these operators: . .* :: ?: sizeof

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:

  • Complex.h: header file for Complex number class
  • tmpComplex.cpp: template for implementation of Complex number class
  • Complex.cpp: finished implementation of Complex number class (from lecture)
  • TestComplex.cpp: driver program to test Complex class