Facebook Page Twitter Page LinkedIn Page
× C Tutorial C Resources


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.

#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 - Operators