Overloading in C++

C++ allows overloading of function definitions, meaning two or more functions can have the same name as long as their parameter lists differ. [It is not enough for their return types to differ.]

Operator Overloading

Operator overloading is one of the key features of C++. Most common operators can be overloaded, and overloaded definitions are expected to be somewhat consistent with their usual functionality.

Rule of Three

If you have a non-trivial destructor, you should also explicitly define a copy constructor and operator=. This is because a non-trivial destructor implies there is dynamic memory allocated for each object. The default copy constructor and operator= implementation will only do a shallow copy, but you likely need a deep copy instead.

Note that operator== is not part of the rule of three because a default version is not provided for your class types - you must always define it explicitly. However, if you have a non-trivial destructor, then probably your equality operator definition needs to be deep, similar to the assignment operator and copy constructor.

Overloading assignment operator

Example prototype for overloading assignment, = on a class named Bag - const Bag& Bag::operator=(const Bag & right). Note the lack of const at the end of the prototype - this operator is expected to change the value of the Bag that appears on the left of the operator in use.

C++ string class operator overloading

Explicit type conversions with classes

Friend Functions

Friend functions enable us to give a [helper, non-class] function access to private members of a particular class. Friends violate the principle of data encapsulation - use as little as possible!!

Overloading via friend functions

If the first argument (left operand) of a binary operator is not of a class type, you can’t overload with a member method. Instead, you can overload with a friend function.

Example for overloading << on a Rational class: