Date Class: Using a class

The Date class has integer variables month, day, and year that are private. We make them private so that we can control the values assigned to them. If they were not private the programmer using the class could assign invalid values to them. Month could be set to 13 or the date could be set to May 40th.

private:
   int month, day, year;

The only way to set the date is through the methods provided which are written to make sure the date is always a valid date. There are two constructors for creating an instance of a date.

The first has no arguments. It will set the date to the current date. The second constructor requires the month, day, and year as arguments. The second requires a string such as "10/31/2016". The 4th requires an integer representing the

  Date(); //constructor for today's date
  Date(int m, int d, int y); //constructor to assign date
  Date(string str); //constructor for today's date as "m/d/year
  Date(int julian); //constructor to convert a Julian date to Date

Here are 4 ways to declare an instance of the Date class:

   Date today;
   Date halloween(10,31,2016);
   Date valentine("2/14/2016");
   Date date2(2457407); //2/8/2016 

To Do:

  • Look at the Date.h code and find the four constructors.
  • Now, look at the Date.cpp code and find the definition for the constructors.
  • Write the C++ program that creates two dates and prints them out.
  • Challenge: Use the < operator to compare them and print in order.

NEXT: Class methods