Operator Overloading in C++

The word polymorphism means having many forms. In c++ polymorphism is broadly classified into run time and compile time polymorphism.

Compile time polymorphism is then divided into function overloading and operator overloading.

In this article, we will discuss operator overloading.

  • Operator overloading is used to add additional functionality to the operator
  • It can only be performed with objects
  • In this, we use the operator function where we define the additional functionality
  • There are 2 types, unary operator overloading, and binary operator overloading
  • If we are overloading the unary operator we do not pass any arguments
  • If we are overloading the binary operator we pass one object as an argument

Unary Operator Overloading

Unary operators operate on only one operand. The increment operator ++ and decrement operator — are examples of unary operators.

Syntax:

returnType className :: operator op(){

Function body
}

Code:

C++ Code

#include<iostream>
 
using namespace std;
class parent {
  private:
    int x, y;
  public:
    void input() {
    x=5;
    y=5;
    }
  void operator++() {
    x = x + 2;
    y = y + 2;
  }
  void display() {
    cout << "value of x is : " << x << endl << "value of y is :" << y;
  }
};
int main() {
  parent M;
  M.input(); // M has x and y
  ++M; // M calls the function ++ , where M.x and M.y get incremented 
  M.display();
  return 0;
}

Output:

value of x is: 7
value of y is:7

Binary Operator Overloading

Binary operators are those which require 2 operands. Like +,*,/,- etc. 

Syntax:

returnType className :: operator op(argument){

Function body
}

Example: Write a program to concatenate 2 strings using operator overloading

Input: str1=”aa”  str2=”bb”
Output: aabb

Code:

C++ Code

#include<iostream>

#include<string.h>

using namespace std;
class parent {
  public:
    string name;
  public:
    void input(string str) {
   this->name = str;
    }
  parent operator + (parent M) { // here q gets passed as an argument
    parent T;
    name+= M.name; // name here is p.name because p is the calling object .
    // we concatenate p.name with q.name and that gets saved in p.name 
    T.name = name; // here we copy p.name to temp object T.name so that we can 
    //return the object
    return T;
  }
  void display() {
    cout << name;
  }

};
int main() {
  parent p, q, r; //We create 3 objects of type parent , each object has a name 
  //variable, i.e, p.name, q.name and r.name
  p.input("xx");
  q.input("yy");
  r = p + q;   //this is equivalent to calling the function as r=p.operator+(q);
  r.display();   //r gets the value from t and concatenation of p.name and 
  //q.name gets printed
  return 0;
}

Output: xxyy

Special thanks to RIshika Gupta for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article