#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 Distance operator + (Distance &amp;, Distance &amp;);
	friend Distance operator - (Distance &amp;, Distance &amp;);
};

Distance operator + (Distance &amp;d1, Distance &amp;d2)
{
	Distance temp;
	temp.feet=d1.feet+d2.feet;
	temp.inch=d1.inch+d2.inch;
	if(temp.inch>11)
	{
		temp.feet++;
		temp.inch = temp.inch %12;
	}
	return temp;
}

Distance operator - (Distance &amp;d1, Distance &amp;d2)
{
	Distance temp;
	temp.feet = d1.feet - d2.feet;
	temp.inch = d1.inch -d2.inch;
	if(temp.inch <0)
	{
		temp.feet--;
		temp.inch = (12+d1.inch) -(d2.inch) ;
	}
	return temp;
}


void main()
{
	clrscr();
	Distance d1,d2,d3;
	d1.setData( 3,8);
	d2. setData(2,11);
	d3=d1-d2;

	d3.getData();

}

Overloading Binary Operator Using Friend Functions (- & +) Distance Class in CPP

Leave a Reply

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