Wednesday, December 5, 2018
Home > OOP > Operator Overloading in C++

Operator Overloading c++

Different types of operators are available in C++. The definition for these operators remains same for already defined data types i.e. int, float, double etc. e.g. + will always add two numbers either they are int, float double. However, we can redefine these operators for user-defined data types like objects. E.g. we can redefine + for objects containing strings to concatenate two strings. We refer it as operator overloading in C++.

Why use operator overloading in c++?

We can write any C++ program without overloading any operator but it helps us to write code in an easy way. It helps us to use built-in operators for user-defined data types.
As discussed above + will always add two numbers for built-in data types but we can also use it to add values for two objects. Below example will explain this in detail.

How to overload operators?

In C++ we can overload an operator using the following syntax:

returnType operator symbol (argument/s)
// body of overloaded operator.        

returnType is same as for the value to be returned (if any) from this function.
operator is the reserved word to be used always when overloading an operator.
symbol is an operator we want to redefine or overload.
Example program: –

#include "stdafx.h"
#include "iostream"
#include "String.h"
using namespace std;

class test
          char str[100];
               strcpy(str, " ");
          test(char sr[])
               strcpy(str, sr);
          test operator +(test t)
               test temp;
               strcpy(temp.str, str);
               strcat(temp.str, t.str);
               return temp;
          void display()
               cout << "******Value after using operator overloading function******\n\n" << str

int main()
     test t1 = "Hi ", t2 = "there ", t3 = "you have done it.", t4;
     t4 = t1 + t2 + t3;
     t4 = t4;
     return 0;

Output: –

Operator Overloading c++ - Operator overloading in c++ example

In the example above we overloaded an operator + to combine/ concatenate two strings. As we know that it is a binary operator so it needs two values.
One thing to be kept in mind is that it is always called with reference of first value/object thus, second value/object is passed as an argument as we have done here.

Note: – operator overloading does not change changes precedence of operators.

Can we overload all operators?

The answer to this question is No, we cannot overload all operators. We cannot overload the following operators in C++.

  1. :: (scope resolution)
  2. . (member selection)
  3. .* (member selection through the pointer to function)
  4. ?: (ternary operator)

Other than these we can overload all operators.

One thought on “Operator Overloading in C++

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.