Design a class called Date that has integer data members to store month, day, and year. The class should have a three-parameter (day-of-month, month, year) default constructor that allows the date to be set at the time a new Date object is created.

Design a class called Date that has integer data members to store month, day, and year.  The class should have a three-parameter (day-of-month, month, year) default constructor that allows the date to be set at the time a new Date object is created.

LANGUAGE: C++

CHALLENGE:

Design a class called Date that has integer data members to store month, day, and year.
The class should have a three-parameter (day-of-month, month, year) default constructor that allows the date to be set at the time a new Date object is created.
If the user creates a Date object without passing any arguments, or if any of the values passed are invalid, the default values of 1, 1, 2001 (i.e., January 1, 2001) should be used (see below for the definition of invalid values).

The class should have member functions to print the date in the following formats:
3/15/13 (printNumerical)
March 15, 2013 (printMonthFirst)
15 March 2013 (printDateFirst)

For the purposes of this exercise, the following are invalid values:
For day of month: any value less than 1 or greater than 31 (so February 30 or April 31 would be acceptable)
For month: any value less than 1 or greater than 12
For year: any value less than 0

SOLUTION:

class Date{
    private:
        int month, day, year;
    public:
        Date(){
            month = 1;
            day = 1;
            year = 2001;
        }
   
        Date(int m, int d, int y){
            month = m;
            day = d;
            year = y;
            if(m <= 0 || m > 12 || d <= 0|| d > 31 || y < 0){
                month = 1;
                day = 1;
                year = 2001;
            }
        }
   
        void printNumerical(){
            cout << month << "/" << day << "/" << year << endl;
        }
   
        void printMonthFirst(){
            string monthNames[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
            cout << monthNames[month - 1] << " " << day << ", " << year << endl;
        }

        void printDateFirst(){
            string monthNames[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
            cout << day << " " << monthNames[month - 1] << " " << year << endl;
        }
};


Add comment