Operator Overloading

Mechanism of giving special meaning to an operator is called operator overloading. We are familiar with the use of different types of operators with primitive data types. But with abstract data types like stacks, lists, queues etc. we have to define each operator. This is called operator overloading.

Operator overloading is a technique which inhances the extensibility of C++. For example, if we overload an operator, we can achieve different functionalities with that operator. Like "+" operator. We can achieve addition - in case of numbers and concatenation - incase of strings. This is the best example of operator overloading. It means that "+" operator is overloaded for integers and strings. C++ has the ability to provide the operators with a special meaning for a data type.

Which operators can we overload?

There is a range of operators which can be overloaded. It includes unary operators, arithmetic operators, logical operators and many more. We can overload all operators in C++ except:

  • Scope resolution operator (::)
  • Ternary operator (?:)
  • Size of operator (sizeof)
  • Dot operator(. , .*)

Overloading Unary Operator

We are going to overload "--" operator and converting its functionality to "++" operator.

In this example, we have overloaded the pre-decrement operator and now it is working like pre-increment operator.

Overloading Binary Operator

We are going to add "+" operator for adding complex numbers.

Overloading Insertion Operator

Primarily operator used for insertion is the right shift operator used for shifting bits to right. In this example, we will overload thid operator.

Overloading Extraction Operator

Primarily operator used for extraction is the left shift operator used for shifting bits to left. In this example, we will overload thid operator.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Medium

What will be the output of this code?

15 XP~4 min
int a = 10, b = 3;
int result = a / b;
printf("%d", result);
Exercise 2 of 2Easy

What does the modulo operator (%) return?

10 XP~2 min