The Date Class
As an example, let’s create a class that describes a Date object. A Date object represents a calendar date in terms of day, month, and year.
The member data we will need are:
• day, an integer.
• month, an integer.
• year, an integer.
For example, if day == 16, month == 4, and year == 2015, then the date represented by the Date object is April 16, 2015.
The day, month, and year constitute the private member data of our class and should not be directly accessible by a user of a Date object.
Our Date class should feature 2 constructors:
• Date() – the default constructor. This sets the date to the default date of April 16,
2015.
• Date(int d, int m, int y = 2015) – the parameterized constructor. This sets the date to the date specified by the user. Dates should be checked for validity. If no year is specified, then the year is set to 2015.
We should also allow the following functions for our Date objects:
• Set(int d, int m, int y) – resets the date if the input is valid. Returns true if successful, false otherwise.
• GetDay(), GetMonth(), GetYear() – accessor functions which return some private data.
• DisplayDate() – displays the current date in a more readable format. For example,
“April 16, 2015”.
• StrokeOfMidnight() – increments the date by one day.
Before we consider how to implement these functions, we should start by defining the blueprint for our class in the header file.
See date.h.
Now, we need to fill in the date.cpp file which contains the definitions for the functions of our date class. We’ll start with the constructors. Note the Date::Function notation!
• Date() – the default constructor. This sets the date to the default date of April 16,
2015.
• Date(int d, int m, int y = 2015) – the parameterized constructor. This sets the date to the date specified by the user. Dates should be checked for validity. If date is invalid, set to April 16, 2015. If no year is specified, then the year is set to 2015.
Now, we’ll work on the Set function.
Set(int d, int m, int y) – resets the date if the input is valid. Returns true if successful, false otherwise.
For the accessor functions, all we have to do is return the value!
GetDay()
GetMonth()
GetYear()
Use a switch statement to print out the appropriate month name!
DisplayDate()
Add a day – don’t forget to check if you need to increment month and year!
StrokeOfMidnight()
So, now we have the header (which declares our class) and the .cpp file (which defines our class). The driver program will be date_driver.cpp. It’s nothing fancy though, just a C++ program that uses our Date class.