ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Home » C++ solved programs » C++ operator overloading programs

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
ADVERTISEMENT




Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.