Below code demonstrate the operator overloading feature of C++. We are overloading unary operator ++ and — on Distance class and implementing custom logic for the increment and decrement operation. Operator function is member function of Distance class.

/*

Objective: Overload ++ and -- Operator for Distance class.
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;
	}
	void operator ++()
	{
		inch++;
		if (inch>11)
		{
			feet++;
			inch=0;
		}

	}
	void operator -- ()
	{
		inch --;
		if (inch <1)
		{
			feet--;
			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();

}
Output of program

This post was created for BCA Student of Gujarat University studying 3rd Semester.

Overloading Unary Operator Using Member Functions (-,++ and –) in C++ Distance Class

Leave a Reply

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