C++ Operator Overloading


What is operator overloading?

  • In C++, operator overloading is a compile time polymorphism in which the operator is overloaded to provide the special meaning to the user defined data type.
  • It is used to overload the operator in C++ and perform the operation on the user defined data type.

For example:

  • we can overload the ‘+’ operator in a class like String so that we can concatenate two strings by using + and in other classes where arithmetic operators can be overloaded are fractional number, integer, etc.
  • We can overload almost any operator in C++ but there are some of the operators which cannot be overloaded.

Such as:

  • Member selector – (.)
  • Ternary operator – (?:)
  • Scope operator – (::)
  • Member pointer selector – (*)
  • Sizeof

How to implement operator overloading in C++?

The operator overloading can be done by implementing a function like:

  • Member Function
  • Non-member Function
  • Friend Function

The operator overloading function can be a member function if the left operand is an object of that class but if the left operand is not an object then the operator overloading function must be a non-member function.
Operator overloading function can be made friend function if it need to access the private and protected members of class.

Let us have a look at the example:

Some restrictions on Operator Overloading

Restrictions that should be considered while implementing operator overloading are:

  • Number of operands cannot be changed like unary operators remains unary, binary remains binary, etc.
  • Precedence and Associativity of an operator cannot be changes.
  • No new operators can be created only the existing ones can be overloaded.


Like it? Please Spread the word!