Binary Operators Overloading in C++

Posted in /  

Binary Operators Overloading in C++
vinaykhatri

Vinay Khatri
Last updated on April 19, 2024

    Binary operators require two operands to perform the task and using the Operator overloading we can redefine the task of a Binary operator for user-defined class objects.

    The syntax for Binary Operator Overloading function

    return_type operator operator_symbol (Class_Name object_name)
    {
    // redefining the operator task
    }

    Example

    #include <iostream>
    #include<string.h>
    using namespace std;
    
    class Displacement
    {
       private :
          int x;
          char n[20];
    
       public:
            Displacement(int initialize, char name[]) //counstructor
               {
                    x=initialize;
                    strcpy(n,name);
                    cout<<"you have created an object "<<n<<" which need to displace  "<< x <<" units";
                    cout<<endl;
              }           
    
            void operator-(Displacement obj) //operator overloading for + operator
              {
                   x= x - obj.x;
                   cout<<obj.x<<" unit has been deducted from the Displacement object "<<n<<" now final displacement for "<<n<<" is: "<<x;
                   cout<<endl;
               }
       
            void operator+(Displacement obj)   //operator overloading for ++ operator
               {
                  x =x+obj.x;
                  cout<<obj.x<<" units has been added to the Displacement object "<<n<<" and final Displacement for "<<n<<" is: "<<x;
                  cout<<endl;
               }
    };
    int main()
    {
         Displacement d1(200,"d1"); // Displacement object
         Displacement d2(30,"d2");  // Displacement object
    
         d1+d2;
         d2-d1;
         return 0;
    }

    Output

    you have created an object d1 which need to displace  200 units
    you have created an object d2 which need to displace  30 units
    30 units has been added to the Displacement object d1 and final Displacement for d1 is: 230
    230 unit has been deducted from the Displacement object d2 now final displacement for d2 is: -200

    Behind the Code In this example, we have overloaded the + and binary Operators. When we create two class object d1(200,"d1"); and d2(30,"d2"); they invoke their respective constructor and the constructor initializes the values for the x and n. When we write this d1+d2; statement, it means the d1 object will call the void operator+(Displacement obj) member function and pass the d2 as Displacement obj argument. Note: When we create an Operator overloading member function for Binary Operators we have to pass a parameter in the member function, in the above example that parameter was obj and its data type was the class name Displacement. People are also reading:

    Leave a Comment on this Post

    0 Comments