Date Class: Using a class

The overloaded operator < lets us compare two dates. A date is less than another date if it is earlier.

The overloaded operator > compares two dates by converting both dates to Julian integers and comparing the integers using the > operator.

Compare the code in these two functions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//Part of Date.cpp
bool Date::operator<(const Date& otherDate) {
   //A date is less than another date if is earlier
   bool result=false; //assume false until proven true
   if(year<otherDate.year) result=true;
   else if(year==otherDate.year && month<otherDate.month) result=true;
   else if(year==otherDate.year && month==otherDate.month && day<otherDate.day) result=true;
   return result;
}//operator

bool Date::operator>(const Date& otherDate) {
   //Convert both dates to Julian and compare the Julian dates
   int jd1=julian();
   int jd2=otherDate.julian();
   return jd1>jd2;
}//operator
CODE

The program below compares two dates using the overloaded < operator.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "c:/cpp/classes/Date.cpp"
#include <iostream>
using namespace std;
int main() {
   //Use the < operator to compare two dates:
   Date date1(5,21,1986);
   Date date2(1,26,1965);
   if(date1<date2) 
      cout<<date1<<" is earlier than "<<date2<<endl;
   else 
      cout<<date1<<" is later than "<<date2<<endl;
   system("pause");
   return 0;
}//main
CODE

NEXT: The + operator