Binary Operator Overloading

Refers to overloading operators that act on more than one object.

 

In this example, the less than < operator is being overloaded to check the 'GetUp' object against the 'GoToWork' object. In this case, the 'GetUp' object is the calling object and the 'GoToWork' object is the paraemeter being used in the overloaded method:

#include <iostream>
using namespace std;

class times {

private:
	int hrs, mins;

public:
	times(int a, int b) {
		hrs = a ;
		mins = b ;
	}
	bool operator < (times myObj){

		if (hrs < myObj.hrs) {
			return true;
		}
		if (hrs == myObj.hrs && mins < myObj.mins) {
			return true;
		}
		return false ;
	}
} ;

int main() {

	int a, b ;
	cout << "Please enter the hour of your getting up time" << endl ;
	cin >> a ;
	cout << "and the minutes" << endl ;
	cin >> b ;

	times GetUp (a, b);
	times GoToWork (07, 03);

	if (GetUp < GoToWork){
		cout << "You get up before you go to work" << endl ;
	} else {
		cout << "Hmm, temporal shift! You seem to go to work before you get up!" << endl ;
	}

	return 0 ;
}

Compile & Run:

Please enter the hour of your getting up time
8
and the minutes
22
Hmm, temporal shift! You seem to go to work before you get up!

Leave a Reply