Date Class: Using a class

When you declare an instance of the Date class, and put in an invalid date, a default date of January 1, 1970 is assigned. (The Unix Epoch time)

It is the programmers responsibility to make sure the date is valid.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include "c:/cpp/classes/Date.cpp"
#include <iostream>
using namespace std;
int main() {
   //Test by entering an invalid date:
   Date date1;
   int month,day, year;
   cout<<"Enter a month:";
   cin>>month;
   cout<<"Enter the day of the month:";
   cin>>day;
   cout<<"Enter a year:";
   cin>>year;
   date1=Date(month,day,year);
   if(date1.getMonth()!=month || date1.getDay()!=day || date1.getYear()!=year)
      cout<<"That is NOT a valid date\n";
   else cout<<date1.toString()<<endl;
   system("pause");
   return 0;
}
CODE

When designing the Date class I wanted the date to always be valid.

I could have used any date for the default date. I picked the Unix Epoch time. This is an arbitrary date used by Unix which all other dates are measured from.

Note also, that the constructor does not fail or throw an error. It does not print an error message or have any other side effects. A class is written to be used by other programmers. Those programmers need to know that it is safe to use the class without strange messages appearing to confuse the users. It is that programmers responsibility to check if a date is valid or not and handle the error however they want.

NEXT: Comparing dates