Overloading Addition operator in C++

0
94
Recursive factorial function in C++
Overloading Subtraction Operator in C++

Here we have overloaded addition operator for a specific class or one can say addition operator is overloaded for a self-defined data type in C++. The code is:

    #include<iostream>
    using namespace std;
     
    class point{
    private:
        int x,y;
     
    public:
        point()
        {
            x =0;
            y = 0;
        
        }
     
        
        friend ostream&operator<< (ostream& cin, point& z){
        
            cin<<z.x<<”  “<<z.y<<endl;
            return cin;
        }    
     
        friend istream&operator>>(istream& a, point> z)
        {
        
            a>>z.x;
            a>>z.y;
            return a;
        }
     
        point&operator+(point& a) //addition operator overloaded function
        {
            a.x = a.x + x;
            a.y = a.y + y;
     
            return a;
            
        }
    };
     
    int main(){
        point n,m;
     
        cout<<“enter values for num1 :”;
        cin>>n;
     
        cout<<“enter values for num2 : “;
        cin>>m;
        
        cout<<“the sum is :”;
        cout<<n+m<<endl;
    }


In the above code, we defined the class point with its attributes, then we defined its operator overloading function for addition operator, inside this function we added the “x” variables separately and the “y” variables separately of the given points. In the main() function the user is asked to enter values for the two point objects, and then the two point objects are added through the overloaded addition operator.

Recursive factorial function in C++
Overloading Subtraction Operator in C++

Leave a Reply