[Exercise 5]

Design and implement a class "Date"

description | hints | solution | discussion
exercises after lesson "More on Classes"
list of all exercises

In our quest to transform our person sorting program to C++, the next task is to transform the struct Date into a class, too. As a date class is useful in many contexts, it is useful to implement a more elaborate class this time.

Implement the following functionality:

a)A constructor(day,month,year) which can be called with 0, 1, 2, or 3 arguments. Missing values are initialized with values from "today". For example, if it is called without arguments, the date is initialized to "today". If it is called with 2 values (day and month), the year is taken from today's date.
b)Member access functions which return the day, month, year, and julian day (see below).
c)An operator-() which computes the number of days between two given dates.
d)The output operator operator<<().

To give you a start, you will find some auxillary functions in the file dateutil.cpp (*).

jday:Takes day,month,year ⇒ returns julian day number.
dmy:Takes julian day number ⇒ returns day,month,year.
today:Shows how to determine today's date under UNIX.

The julian day number was invented and is used by astronomers. They just picked a special day (Januar 1, 4713 B.C.) and continuously number the days since then.

The program "test5.cpp" can be used for testing.

Additional hints

Solution:

Alternative solution:

Discussion of solution (*)