Overloading Subtraction Operator in C++

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

    using namespace std;
    class point{
        int x,y;
            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)
            return a;
        point&operator-(point& a)
            a.x = a.x - x;
            a.y = a.y - y;
            return a;
    int main(){
        point n,m;

In the above code, we defined the class point with its attributes, then we defined its operator-overloading/”>operator overloading function for subtraction operator, inside this function we subtracted 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 subtracted through the overloaded subtraction operator.

Latest Content