Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++ Design a class called Date that has integer data members to store month, day

ID: 3805868 • Letter: C

Question

C++

Design a class called Date that has integer data members to store month, day, and year. The class should have a three-parameter default constructor that allows the date to be set at the time a new Date object is created. If the user creates a Date 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. The class should have member functions to print the date in the following formats:

3/15/13

March 15, 2013

15 March 2013

Demonstrate the class by writing a program that uses it. Be sure you program only accepts reasonable values for month and day. The month should be between 1 and 12. The day should be between 1 and the number of days in the selected month.

Explanation / Answer

#include <iostream>
#include <string>
using namespace std;

static string monthName[] = {"January", "February","March","April", "May", "June", "July","August", "September", "October","November", "December" };

class Date
{
private:
   int month, day, year;
   public:
  
   Date() //default constructor
   {
       month = 1, day = 1, year = 2001;
   }
   Date(int month, int day, int year) //parameterized constructor
   {
   this->month = month;
   this->day = day;
   this->year = year;
   }
  
   void setDay(int day)    //set day with validation
   {
        if(month == 2 && day < 1 || day > 28) //february
        cout << "The day is invalid" << endl;
   else if (day < 1 && day > 31)
       cout << "The day is invalid" << endl;
   else
   this->day = day;
   }
  
   void setMonth(int month) //set month with validation
   {
   if (month < 1 && month > 12)
       cout << "The month is invalid" << endl;
   else
   this->month = month;
  
}
  
   void setYear(int)
   {
       this->year = year;
   }
  


void print()
{
   cout << month << "/" << day << "/" << (year-2000) << endl;

     cout << monthName[month - 1] << " " << day << "," << year << endl;

   cout << day << " " << monthName[month - 1] << " " << year << endl;
}
};

int main()
{
   int Month, Day, Year;
  

   cout << "Please enter a month (between 1 - 12) " << endl;
   cin >> Month;
  
   cout << "Please enter a day (between 1 - 31) " << endl;
   cin >> Day;
  
   cout << "Please enter a year " << endl;
   cin >> Year;
      
  
   Date Date1(Month, Day, Year);
   Date1.print();

  
   return 0;
}

Output:

Please enter a month (between 1 - 12) 3

Please enter a day (between 1 - 31) 15

Please enter a year 2013

3/15/13

March 15, 2013

15 March 2013

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote