Overloading Operators

An overloaded operator has more than one meaning. Note that the standard arithmetic operators in C++ already have multiple meanings.

To overload an operator, you define an operator function whose name has the form
operatorsymbol where symbol is the operator you want to overload
i.e. for an assignment operator, you name the function operator= and declare one argument: the object that is to be copied. For example, to provide an assignment operator for the class numArray, you would add the declaration
virtual void operator=(const numArray& Arr) to the class definition.
This overloaded assignment operator is used whenever you assign one object to another.

Guidelines for Overloading Operators

  1. You can overload any C++ operator except  .  .*  ::  ?:  sizeof
  2. You cannot define new operators by overloading symbols that are not already operators in C++
  3. You cannot change the standard precedence of a C++ operator or the number of its operands
  4. At least one operand of an overloaded operator must be an instance of a class
  5. A typical class should overload at least the assignment(=) and the equality (==) operators

Example:

void NumArray::operator=(const NumArray& NArr)
	// assigns the contents of NArr to the object of class NumArray
{
	size = NArr.size; 	// copy size of old array

	// copies all of the elements of the old array
	for (int count = 0; count < size; count++)
	{
		ele[count] = NArr.ele[count];
	}
}

Friends or Members?

An overloaded operator function should be a friend of the class if: An overloaded operator function should be a member of the class if: For most operators, these guidelines are stylistic guidelines. However, =, [], (), and -> cannot be declared as friends.