Function Overloading

Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. Overloading allows you to create multiple functions of the same name with different implementations.

  • two or more methods in one class have the same method name but different in # or types of parameters

When a function name is overloaded with different jobs it is called Function Overloading. In Function Overloading “Function” name should be the same and the arguments should be different. Function overloading can be considered as an example of a polymorphism feature in C++.

We can do this for regular functions or for Constructor overloading operator overloading

Overloading vs Overriding

Operator Overloading

Seen in CS247 - Software Engineering Principles To perform an operator overload, we define a function with the name “operator” concatenated with the operator symbol.

```cpp
operator+, operator>>, operator!, operator==

The number of args must match the arity of the operator. eg:

    • : binary operator - 2 args
  • ! : unary operator - 1 arg

Example:

// defined inside the class Rational
Rational& operator=(const Rational& rhs) {
	num = rhs.num;
	denom = rhs.denom;
	return *this;
}

Certain Operator overloads need to be inside the class

There are some operator overloads that MUST be defined as methods (as opposed to standalone functions). These are:

  • operator=
  • operator[]
  • operator→
  • operator()
  • operator T where T is a type

Remember that when you implement an operator overload as a method of a class, this is the LHS, and the RHS is the argument passed to the operator.