C++ Programming/Operators/Operator Overloading

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Operator overloading

Introduction

To overload an operator is to provide it with a new meaning for user-defined types. This is done in the same fashion as defining a function. The basic syntax follows (where @ represents a valid C++ operator):

 return_type operator@(parameter_list)
 {
   ... // definition
 }

Not all operators may be overloaded, new operators cannot be created, and the precedence, associativity or arity of operators cannot be changed (for example ! cannot be overloaded as a binary operator). Most operators may be overloaded as either a member function or non-member function, some, however, must be defined as member functions. Operators should only be overloaded where their use would be natural and unambiguous, and they should perform as expected. For example, overloading + to add two complex numbers is a good use, whereas overloading * to push an object onto a vector would not be considered good style.

Operators as member functions

Operators may be overloaded as member or non-member functions. Aside from the operators which must be members, the choice of whether or not to overload as a member is up to the programmer. Operators are generally overloaded as members when they:

  1. change the left-hand operand, or
  2. require direct access to the non-public parts of an object.

When an operator is defined as a member, the number of explicit parameters is reduced by one, as the calling object is implicitly supplied as an operand. Thus, binary operators take one explicit parameter and unary operators none. In the case of binary operators, the left hand operand is the calling object, and no type coercion will be done upon it. This is in contrast to non-member operators, where the left hand operand may be coerced.

 // binary operator as member function
 Vector2D Vector2D::operator+(const Vector2D& right) {...}
 // binary operator as non-member function
 Vector2D operator+(const Vector2D& left, const Vector2D& right) {...}
 // unary operator as member function
 Vector2D Vector2D::operator-() {...}
 // unary operator as non-member function
 Vector2D operator-(const Vector2D& vec) {...}

Overloadable operators

Arithmetic operators
  • + (addition)
  • (subtraction)
  • * (multiplication)
  • / (division)
  • % (modulus)

As binary operators, these involve two arguments which do not have to be the same type. These operators may be defined as member or non-member functions. An example illustrating overloading + for the addition of a 2D mathematical vector type follows.

 Vector2D operator+(const Vector2D& left, const Vector2D& right)
 {
   Vector2D result;
   result.set_x(left.x() + right.x());
   result.set_y(left.y() + right.y());
   return result;
 }

It is good style to only overload these operators to perform their customary arithmetic operation.

Bitwise operators
  • ^ (XOR)
  • | (OR)
  • & (AND)
  • ~ (complement)
  • << (shift left, insertion to stream)
  • >> (shift right, extraction from stream)

All of the bitwise operators are binary, excepting complement, which is unary. It should be noted that these operators have a lower precedence than the arithmetic operators, so if ^ were to be overloaded for exponentation, x ^ y + z may not work as intended. Of special mention are the shift operators, << and >>. These have been overloaded in the standard library for interaction with streams. When overloading these operators to work with streams the rules below should be followed:

  1. overload << and >> as non-members (the left operand should be the stream - cout << 3, not 3 << cout)
  2. the stream must be passed by references (input/output modifies the stream, and copying is not allowed)
  3. the operator should return a reference to the stream it receives (to allow chaining, cout << 3 << 4 << 5)

An example using a 2D vector:

 ostream& operator<<(ostream& out, const Vector2D& vec) // output
 {
   out << "(" << vec.x() << ", " << vec.y();
   return out;
 }
 istream& operator>>(istream& in, Vector2D& vec) // input
 {
   double x, y;
   in >> x >> y;
   vec.set_x(x);
   vec.set_y(y);
   return in;
 }
Assignment operator

The assignment operator, =, must be a member function, and is given default behaviour for user-defined classes by the compiler, performing a copy of every member using its copy constructor. This behaviour is generally acceptable for simple classes which only contain variables. However, where a class contains references or pointers to outside resources, the assignment operator should be overloaded (as general rule, whenever a destructor and copy constructor are needed so is the assignment operator), otherwise, for example, two strings would share the same buffer and changing one would change the other.

In this case, an assignment operator should perform two duties:

  1. clean up the old contents of the object
  2. copy the resources of the other object

In addition, before doing anything, the assignment operator should check for self-assignment, which generally will not work (as when the old contents of the object are erased, they cannot be copied to refill the object).

Another common use of overloading the assignment operator is to declare the overload in the private part of the class and not define it. Thus any code which attempts to do an assignment will fail on two accounts, first by referencing a private member function and second fail to link by not having a valid definition. This is done for classes where copying is to be prevented, and generally done with the addition of a privately declared copy constructor

Example
class DoNotCopyOrAssign {
public:
    DoNotCopyOrAssign() {};
private:
    DoNotCopyOrAssign(DoNotCopyOrAssign const&);
    DoNotCopyOrAssign &operator=(DoNotCopyOrAssign const &);
};
class MyClass : public DoNotCopyOrAssign {
public:
  MyClass();
};
MyClass x, y;
x = y; // Fails to compile due to private assignment operator;
MyClass z(x); // Fails to compile due to private copy constructor.
Relational operators
  • == (equality)
  • != (inequality)
  • > (greater-than)
  • < (less-than)
  • >= (greater-than-or-equal-to)
  • <= (less-than-or-equal-to)

All relational operators are binary, and should return either true or false. Generally, all six operators can be based off a comparison function, or each other, although this is never done automatically (e.g. overloading > will not automatically overload < to give the opposite).

Logical operators
  • ! (NOT)
  • && (AND)
  • || (OR)

The ! operator is unary, && and || are binary. It should be noted that in normal use, && and || have "short-circuit" behaviour, where the right operand may not be evaluated, depending on the left operand. When overloaded, however, this behaviour is lost.

Compound assignment operators
  • += (addition-assignment)
  • –= (subtraction-assignment)
  • *= (multiplication-assignment)
  • /= (division-assignment)
  • %= (modulus-assignment)
  • &= (AND-assigment)
  • |= (OR-assignment)
  • ^= (XOR-assignment)
  • >>= (shift-right-assignment)
  • <<= (shift-left-assignment)

Compound assignment operators should be overloaded as member functions, as they change the left-hand operand. Like all other operators (except basic assignment), compound assignment operators must be explicitly defined, they will not be automatically (e.g. overloading = and + will not automatically overload +=). A compound assignment operator should work as expected: A @= B should be equivalent to A = A @ B. An example of += for a two-dimensional mathematical vector type follows.

 Vector2D& Vector2D::operator+=(const Vector2D& right)
 {
   *this = *this + right;
   return *this;
 }
Increment and decrement operators
  • ++ (increment)
  • – – (decrement)

Increment and decrement have two forms, prefix (++i) and postfix (i++). To differentiate, the postfix version takes a dummy integer. Increment and decrement operators should be member functions. The prefix version should return a reference to the changed object. The postfix version should just return the original value. In a perfect world, A += 1, A = A + 1, A++, ++A should all leave A with the same value.

 SomeValue& SomeValue::operator++() // prefix
 {
   ++data;
   return *this;
 }
 SomeValue SomeValue::operator(int unused) // postfix
 {
   SomeValue result = *this;
   ++data;
   return result;
 }

Often one operator is defined in terms of the other for ease in maintence, especially if the functon call is complex.

 SomeValue SomeValue::operator(int unused) // postfix
 {
   SomeValue result = *this;
   ++(*this); // call SomeValue::operator++()
   return result;
 }
Subscript operator

The subscript operator, [ ], is a binary operator which must be a member function (hence it takes only one explicit parameter, the index). The subscript operator is not limited to taking an integral index. For instance, the index for the subscript operator for the std::map template is the same as the key of the key, so it may be a string etc. The subscript operator is generally overloaded twice; as a non-constant function (for when elements are altered), and as a constant function (for when elements are only accessed).

Function call operator

The function call operator, ( ), is generally overloaded to create objects which behave like functions, or for classes that have a primary operation. The function call operator must be a member function, but has no other restrictions - it may be overloaded with any number of parameters of any type, and may return any type. A class may also have several definitions for the function call operator.

comma operator

The comma operator,() , can be overloaded. The language comma operator has left to right precedence, the operator,() has function call precedence, so be aware that overloading the comma operator has many pitfalls.

Example
MyClass operator,(MyClass const &, MyClass const &);
MyClass Function1();
MyClass Function2();
MyClass x = Function1(), Function2();
For non overloaded comma operator, the order of execution will be Function1(), Function2(); With the overloaded comma operator, the compiler can call either Function1(), or Function2() first.


Member access operators
Memory management operators
  • new (allocate memory for object)
  • new[ ] (allocate memory for array)
  • delete (deallocate memory for object)
  • delete[ ] (deallocate memory for array)

The memory management operators can be overloaded to customise allocation and deallocation (e.g. to insert pertinent memory headers). They should behave as expected, new should return a pointer to a newly allocated object on the heap, delete should deallocate memory, ignoring a NULL argument. To overload new, several rules must be followed:

  • new must be a member function
  • the return type must be void*
  • the first explicit parameter must be a size_t value

To overload delete there are also conditions:

  • delete must be a member function (and cannot be virtual)
  • the return type must be void
  • there are only two forms available for the parameter list, and only one of the forms may appear in a class:
    • void*
    • void*, size_t
Conversion operators

Conversion operators enable objects of a class to be either implicitly (coercion) or explicitly (casting) converted to another type. Conversion operators must be member functions, and should not change the object which is being converted, so should be flagged as constant functions. The basic syntax of a conversion operator declaration, and declaration for an int-conversion operator follows.

 operator type() const; // const is not necessary, but is good style
 operator int() const;

Notice that the function is declared without a return-type, which can easily be inferred from the type of conversion. Including the return type in the function header for a conversion operator is a syntax error.

 double operator double() const; // error - return type included
Operators which cannot be overloaded
  • ?: (conditional)
  • . (member selection)
  • .* (member selection with pointer-to-member)
  • :: (scope resolution)
  • sizeof (object size information)
  • typeid (object type information)