



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




If you forget the & and pass by value, the object will be copied which is expensive for containers with lots of elements. Note: This is unlike arrays, which are not copied when passed by value.
// Program: date_main.cpp // Purpose: Demonstrate use of the Date class.
#include
int main() { std::cout << "Please enter today’s date.\n" << "Provide the month, day and year: "; int month, day, year; std::cin >> month >> day >> year; Date today(month, day, year);
Date tomorrow(today.getMonth(), today.getDay(), today.getYear()); tomorrow.increment();
std::cout << "Tomorow is "; tomorrow.print(); std::cout << std::endl;
Date Sallys_Birthday(9,29,1995); if (sameDay(tomorrow, Sallys_Birthday)) { std::cout << "Hey, tomorrow is Sally’s birthday!\n"; }
std::cout << "The last day in this month is " << today.lastDayInMonth() << std::endl; return 0; }
Add code to date_main.cpp to read in another date, check if it is a leap-year, and check if it is equal to tomorrow. Output appropriate messages based on the results of the checks.
int Date::getDay() const { return day; }
int Date::getMonth() const { return month; }
int Date::getYear() const { return year; }
void Date::setDay(int d) { day = d; }
void Date::setMonth(int m) { month = m; }
void Date::setYear(int y) { year = y; }
void Date::increment() { if (!isLastDayInMonth()) { day++; } else { day = 1; if (month == 12) { // December month = 1; year++; } else { month++; } } }
bool Date::isEqual(const Date& date2) const { date2.getDay(); return day == date2.day && month == date2.month && year == date2.year; }
bool Date::isLeapYear() const { return (year%4 ==0 && year % 100 != 0) || year%400 == 0; }
int Date::lastDayInMonth() const { if (month == 2 && isLeapYear()) return 29; else return DaysInMonth[ month ]; }
bool Date::isLastDayInMonth() const { return day == lastDayInMonth(); // uses member function }
void Date::print() const { std::cout << month << "/" << day << "/" << year; }
bool sameDay(const Date& date1, const Date& date2) { return date1.getDay() == date2.getDay() && date1.getMonth() == date2.getMonth(); }
These are special functions that initialize the values of the member variables. You have already used constructors for string and vector objects.
Member functions are like ordinary functions except:
For the Date class:
More on member functions:
The code for the Date example is in three files: