Write a Date C++ class to model a calendar date. Show your Date class in action
ID: 3539898 • Letter: W
Question
Write a Date C++ class to model a calendar date.
Show your Date class in action by writing a C++ application that constructs an object called birthday. Initialize the birthday object with the date 6/7/1991.
Your application should then show the use of an accessor member function, namely printDate(), to print the date stored in the object to the console (i.e., using cout). The printDate() member function must show the month using the name of the month (and not as an integer).
Finally, show what happens if a Date object is constructed using an invalid Date, for example, 15/55/2013. Write your printDate() member function to display an error message for invalid dates. In particular, the Date 15/55/2013 object should display the following message from the printDate() member function
Explanation / Answer
#include<iostream>
#include<fstream>
using namespace std;
class date{
private:
int day, year, mz; /* day, year and mz are the variables storing date, year and month number respectively */
string mo[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}, month; /* mo is an array variable storing all months name and month variable stores the month name corresponding to month number mz */
public:
date(int d, int m, int y){ /* constructor initializing the date, month name, month number and year */
day = d;
month = mo[m - 1];
mz = m;
year = y;
}
void printDate(){ // function to print the date
if(day <= 30 && (mz == 4 || mz == 6 || mz == 9 || mz == 11)){ /*checking the validity of dates corresponding to months */
cout << "The date is " << day << " " << month << ", " << year << endl;
}
else if(day <= 31 && (mz == 1 || mz == 3 || mz == 5 || mz == 6|| mz == 7 || mz == 8|| mz == 10 || mz == 12)){ /*checking the validity of dates corresponding to months */
cout << "The date is " << day << " " << month << ", " << year << endl;
}
else if(day <= 28 && year % 4 != 0 && mz == 2){ /* checking the validity of dates in february in non-leap year */
cout << "The date is " << day << " " << month << ", " << year << endl;
}
else if(day <= 29 && year % 4 == 0 && mz == 2){ /* checking the validity of dates in february in non-leap year */
cout << "The date is " << day << " " << month << ", " << year << endl;
}
else cout << "The date is WRONG" << endl;
}
};
int main(){
date birthday(6, 7, 1991); // declaring and initializing the birthday object
birthday.printDate(); // calling the printDate function
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.