C++ program to add two objects using binary plus (+) operator overloading

This program will demonstrate example of Binary Plus Operator Overloading, in this program we will take two objects and adding them.

Adding two objects using binary plus (+) operator overloading program in C++

// C++ program to add two objects using binary
// plus (+) operator overloading

#include <iostream>
using namespace std;

class NUM {
private:
    int n;

public:
    // function to get number
    void getNum(int x)
    {
        n = x;
    }
    // function to display number
    void dispNum(void)
    {
        cout << "Number is: " << n;
    }
    // add two objects - Binary Plus(+) Operator Overloading
    NUM operator+(NUM& obj)
    {
        NUM x; // create another object
        x.n = this->n + obj.n;
        return (x); // return object
    }
};

int main()
{
    NUM num1, num2, sum;
    num1.getNum(10);
    num2.getNum(20);

    // add two objects
    sum = num1 + num2;

    sum.dispNum();
    cout << endl;

    return 0;
}

Output

    Number is: 30





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.