Lecture 6: Operator Overloading

Computer Programming

J Mwaura

Operator Overloading

It is a type of polymorphism in which an operator is overloaded to give user-defined meaning to it

Overloaded operator is used to perform operation on user-defined data type

For example '+' operator can be overloaded to perform addition on various data types, like for Integer, String(concatenation) etc

Roles of an Object

Objects of user-defined types can play three different roles in a function

  • Host object
  • Parameter object
  • Returned object

Understanding objects in each role helps the process of writing overloading operators

1. Host object

It is the one that is pointed to by the pointer

It must be constant if the function is not supposed to change it; it must be non-constant otherwise

2. Parameter object

It must be passed to the member function in three ways:

  • pass-by-value
  • pass-by-reference
  • pass-by-pointer

3. Returned object

Functions may return an object in three ways:

  • pass-by-value
  • pass-by-reference
  • pass-by-pointer

Must use return-by-value if the returned object is created in the body of the function

Must use return-by-reference or by pointer if the returned object is passed as the parameter to the function

Overloading Principles

Operator overloading is the definition of two or more operations using the same operator

  • 14 + 20
  • 14.21 + 20.45

In the following example, the compiler changes the first operand to 14.0 to do the operation

Categories of Operators

  • non-overloadable
  • not recommended for overloading
  • Overloadable

Rules of Overloading

Precedence - No change to the precedence of the operator

Associativity - The operator keeps its associativity

Commutativity - No change to commutativity of the operator

Arity - Unary & binary operators are kept

No new operators - No invention of operators

No combination - No new operators by combining 2 or more operators

End of Lecture 6

Computer Programming

That's it!

Queries about this Lesson, please send them to: jmwaura.uni@gmail.com

*References*

  • C++ Programming - An Object-Oriented Approach, 2019 Behrouz, Richard et.al
  • Accelerated C++ - Practical Programming by Example, 2000 Andrew, Barbara et.al
Courtesy of
Computer Programming