Written by Sai Sandeep Thota on April 27, 2013 in C++ > Programming

C++ Program to Add Two Numbers using Operator Overloading

GET ALERTS:

Get our Latest updates delivered to your mailbox!

In this program we can perform addition of two numbers using Operator overloading. Binary operators will require one object as argument so they can perform the operation. If we are using Friend functions here then it will need two arguments.

So why do we need one object as an argument here? To understand this, you’ll need to know how the operator is being invoked:ob1+ob2. The object before the operator will invoke the function and the object after the operator will be passed as an argument to the function. So in this case ob1 is invoking object and ob2 is passed as argument to the function.

We are passing 10, 20 as the values of ob1’s x and y and 20, 30 as the values of ob2’s x and y.

The operator+(sum &ob) explanation:

void sum::operator+(sum &ob) {
	x=x+ob.x;
	y=y+ob.y;
	display();
}

In the above function, we have an object as a parameter. The passed parameter ob is none other than ob2. So ob2.x means 20 and ob2.y means 30. We don’t require ob for other x and y as they are having the values of the invoked object (x=10, y=20). Then we are calling the display() function which we have written in the class.

C++ Program to Add Two Numbers using Operator Overloading

#include<conio.h>
#include<iostream.h>

class sum {
	public:
	int x, y, z;
	void getdata(int a, int b)
	{
		x=a;
		y=b;
	}

	void display()
	{
		cout<<"\nSum of X:"<<x;
		cout<<"\nSum of Y:"<<y;
	}

	void operator+(sum &);
};

void sum::operator+(sum &ob) {
	x=x+ob.x;
	y=y+ob.y;
	display();
}

void main()
{
	sum ob1, ob2;
	clrscr();
	ob1.getdata(10,20);
	ob2.getdata(20,30);
	ob1+ob2;
	getch();
}

Output:
sum

{ 2 comments… read them below or add one }

Nitin July 20, 2013 at 11:09 pm

Pls share a link to downTurbo C++ IDE for Windows 7

Reply

Sai Sandeep Thota August 2, 2013 at 8:22 pm

Leave a Comment

Previous post:

Next post: