C++ Tutorial C++ Advanced C++ Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

C++ - Binary Operator Overloading



Binary operators are those operators which requires two operand to produce a new value. Following is the list of binary operators that can be overloaded in C++.

Overloadable binary operators in C++
+-*/=<>
+=-=*=/===<<>>
<<=>>=!=<=>=%^
|&=^=|=&&||%=
[],->*->&

Example: Overloading Binary Operators

In the example below, binary operators - +, -, *, and / are overloaded. When it is applied with vector objects, it performs addition, subtraction, multiplication and division component wise. For example:

  • (10, 15) + (5, 25) will produce (10+5, 15+25) = (15, 40)
  • (10, 15) - (5, 25) will produce (10-5, 15-25) = (5, -10)
  • (10, 15) * (5, 25) will produce (10*5, 15*25) = (50, 375)
  • (10, 15) / (5, 25) will produce (10/5, 15/25) = (2, 0.6)
#include <iostream>
using namespace std;
 
class Vector {
  public:
    float x, y;
    //class constructor
    Vector(){}
    Vector(float x, float y) {
      this->x = x;
      this->y = y;
    }
    //function to display vector
    void displayVector() {
      cout<<"("<<x<<", "<<y<<")\n"; 
    }
    //function for overloading binary +
    Vector operator+ (const Vector v) {
      float X =  this->x + v.x;
      float Y =  this->y + v.y;  
      return Vector(X, Y);  
    }
    //function for overloading binary -
    Vector operator- (const Vector v) {
      float X =  this->x - v.x;
      float Y =  this->y - v.y;  
      return Vector(X, Y);  
    }
    //function for overloading binary *
    Vector operator* (const Vector v) {
      float X =  this->x * v.x;
      float Y =  this->y * v.y;  
      return Vector(X, Y);  
    }
    //function for overloading binary /
    Vector operator/ (const Vector v) {
      float X =  this->x / v.x;
      float Y =  this->y / v.y;  
      return Vector(X, Y);  
    }            
};
int main (){
  Vector v1(10, 15), v2(5, 25), v3;

  v3 = v1 + v2 ;
  v3.displayVector();
  v3 = v1 - v2 ;
  v3.displayVector();
  v3 = v1 * v2 ;
  v3.displayVector();
  v3 = v1 / v2 ;
  v3.displayVector();
    
  return 0;
}

The output of the above code will be:

(15, 40)
(5, -10)
(50, 375)
(2, 0.6)

❮ C++ - Operator Overloading

5