Operator Overloading - Part 03 Overloading Unary Operator using Friend Function
Operator Overloading – Part 03 Overloading Unary Operator using Friend Function
/*

Objective: Overload ++ and -- Operator for Distance class using Friend Function
Author: Amit Kumar Trivedi

*/

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

class Distance
{
	public:
	int feet;
	int inch;
	void setData(int x, int y)
	{
		feet=x;
		inch=y;
	}
	void getData()
	{
		cout<<feet<<" feet "<<inch <<" inch"<<endl;
	}

	friend void operator ++(Distance &d);
	friend void operator -- (Distance &d);
};

void operator ++(Distance &d)
{
	d.inch++;
	if (d.inch>11)
	{
		d.feet++;
		d.inch=0;
	}
}

void operator -- (Distance &d)
{
	d.inch --;
	if (d.inch <1)
	{
		d.feet--;
		d.inch=11;
	}
}

void main ()
{
	clrscr();

	Distance obj;  //user defined class object
	obj.setData(5,11);
	obj.getData();
	obj++;
	cout<<"After applying ++ operator"<<endl;
	obj.getData();
	obj--;
	cout<<"After applying -- operator"<<endl;
	obj.getData();
	getch();

}
Operator Overloading – Part 03 Overloading Unary Operator using Friend Function in C++

Leave a Reply

Your email address will not be published. Required fields are marked *