Operator Overloading Programming Exercise 1

Operator overloading defines an additional meaning of operator.

Operator overloading is a feature of C++ programming language that allows a programmer to redefine the meaning of operator when they operate on class object.

If you don’t familiar with operator overloading please read the following article first.

What is Class?

Class may be defined as the collection of objects which have some properties and functions.

If you want to know more about classes, please read the following article.

Write a class Time that has three data member hour, minutes and
seconds. The class has the following member functions;
 A constructor to initialize the time.
 Show function to show the time.
 Overload ++ operator to increase the time by 1 minute.
 Overload — operator to decrease the time by 1 minute.

#include<iostream>
using namespace std;

class Time
{
	private:
		int h, m, s;
		public:
			Time()
			{
				h = m= s = 0;
			}
			Time(int hh, int mm, int ss)
			{
				h = hh; m = mm; s = ss;
			}
			void operator ++(int)
			{
				if(m == 59)
				{
					m = 0;
					h++;
				}
				else
				m++;
			}
			void operator --(int)
			{
				if(m == 0)
				{
					m = 59;
					h--;
				}
				else
				m--;
			}
			void show()
			{
				cout<<h<<";"<<m<<";"<<s<<endl;
			}
};
     main()
     {
     	Time x(10, 50, 50);
     	x.show();
     	x++;
     	x.show();
     	x--;
     	x.show();
     }

Leave a Reply