Practice Problem: Write a class

I'd like us to write a class called Date. This class will be used to store normal calendar dates. The class should contain three private data variables:

It should also contain the following public member functions:

Beyond that, feel free to build the class however you want. I'm planning to add a private member function

bool isValidDate(unsigned inMonth, unsigned inDay, unsigned inYear)

to help make the code easier to read.

As per usual, we're going to build this together and talk about the different decisions we make as we go. You can find the final result below.

If you get bored:

Add a public member function called incrementDate. This should change the date to whatever the next calendar date happens to be. For example:

Date date(1,4,2009);
date.incrementDate();  // now date is 1/5/2009

Date date2(3,31,2015);
date2.incrementDate();   // now date2 is 4/1/2015

Finished Version

Date.cpp
Date.h
DateTest.cpp

Some additional functions

One thing that can be confusing when working with classes is how we refer to our class member in different circumstances. For example:

  // How to use setDate from main() 
  int main() {
      Date exampleDate;

      // use the setDate function in exampleDate
      exampleDate.setDate(3, 12, 1990);

      // stuff here
  }

  // How to use setDate from inside class definition of Date
  // This is copy-pasted from the Date(unsigned, unsigned, unsigned) constructor
  //  in Date.cpp
  Date::Date(unsigned inMonth, unsigned inDay, unsigned inYear) {
      setDate(inMonth, inDay, inYear);
  }

Hopefully this makes sense. Each time we use the setDate function, c++ needs to understand which Date object we are using setDate on. Working in main, I write NAME_OF_DATE_OBJECT.setDate(...) to explain that I am using setDate on that particular object. When inside the class definition of Date, there is already one obvious choice of Date object to use setDate on. That is whatever Date object I'm already working with. We'll try to explain this better by writing an example function.

Next Problem

Create a function called dateEquals. It should accept two objects of type Date, and return true if the Dates are equal, false if they are not.

Next, create a member function of the Date class called equals. With this equals function I want to be able to run the following code:

  Date date1, date2;
  // Initialize date1 and date2 somehow here
  date1.equals(date2); // should be true when date1, date2 are equal. False otherwise

Here is an updated version of our Date class with both of the above functions.

Date.cpp
Date.h
DateTest.cpp