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

C++ Program to Implement Operator Overloading

GET ALERTS:

Get our Latest updates delivered to your mailbox!

What not you can do with Object oriented programming. You have the power to do anything. Operator Overloading allows you to perform operations on Objects. For example if you want to change the values of variables to negative we can call the respective object by placing an appropriate operator infront of the object.

If we want to change the values of variables of ob1 to negative we can simply call -ob1 in the main program. You will need to write a function for operator overloading inorder to achieve this.

Operator overloading can be defined by the following syntax:
return-type operator symbol();. For example if we want to implement subtraction operation with no returns then the syntax will look like: void operator-();. Here operator is a keyword.

You can read out this section for all other Operator Overloading explanations.

Opeartor Overloading

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

class data {
	public:
	int x, y;
	void setdata(int a, int b)
	{
		x=a;
		y=b;
	}
	void display()
	{
		cout<<"\nX="<<x;
		cout<<"\nY="<<y;
	}
	void operator-();
};

void data::operator-()
{
	x=-x;
	y=-y;
}

void main()
{
	data ob1, ob2;
	clrscr();
	ob1.setdata(10,20);
	ob2.setdata(30,40);
	cout<<"\nob1 Display:";
	ob1.display();
	cout<<"\nob2 Display:";
	ob2.display();
	-ob1;
	cout<<"\nob1 Display after invoiking Operator";
	ob1.display();
	getch();
}

Operator Overloading using Friend Functions

Friend functions take an class as an argument/parameter and performs appropriate operation.

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

class data {
	public:
	int x, y;
	void setdata(int a, int b)
	{
		x=a;
		y=b;
	}
	void display()
	{
		cout<<"\nX="<<x;
		cout<<"\nY="<<y;
	}
	void friend operator-(data &);
};

void friend operator-(data ob)
{
	ob.x=-ob.x;
	ob.y=-ob.y;
}

void main()
{
	data ob1, ob2;
	clrscr();
	ob1.setdata(10,20);
	ob2.setdata(30,40);
	cout<<"\nob1 Display:";
	ob1.display();
	cout<<"\nob2 Display:";
	ob2.display();
	-ob1;
	cout<<"\nob1 Display after invoiking  '-' Operator";
	ob1.display();
	getch();
}

Output:
operator-

{ 1 comment… read it below or add one }

Il viaggio di Ulisse. Da Troia a Itaca May 4, 2014 at 6:03 pm

I really like it when people come together and
share thoughts. Great site, continue the good work!

Reply

Leave a Comment

Previous post:

Next post: