C++ Tutorial C++ Advanced C++ References

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;

  //using overloaded binary operators
  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