#include #include #include // for the functions time and localtime using namespace std; class date { // Declarations for data members: int year; int month; // in the range 1 to 12 inclusive int day; // in the range 1 to 31 inclusive static const int length[13]; // Static data member for month lengths public: // Constructor declarations date(int m, int d, int y); // Existing constructor date(); // New constructor that initializes to today's date // Member function declarations void print() const; // Print function void next(int n); // Advance n days void next(); // Advance one day int dayOfYear() const; // New function to return day of the year // Friend function declaration friend int distance(const date& d1, const date& d2); }; const int date::length[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // Constructor initializing date with given values date::date(int m, int d, int y) { year = y; if (m < 1 || m > 12) { throw invalid_argument("bad month"); } month = m; if (d < 1 || d > length[month]) { throw invalid_argument("bad day of the month"); } day = d; } // New constructor initializing date to today's date date::date() { time_t now = time(nullptr); tm *p = localtime(&now); year = p->tm_year + 1900; month = p->tm_mon + 1; day = p->tm_mday; } // Print function void date::print() const { cout << month << "/" << day << "/" << year; } // Function to move date forward by n days void date::next(int n) { for (int i = 0; i < n; ++i) { next(); } } // Function to move date forward by one day void date::next() { if (day < length[month]) { ++day; } else { day = 1; if (month < 12) { ++month; } else { month = 1; ++year; } } } // Function to calculate day of the year int date::dayOfYear() const { int dayOfYear = day; for (int i = 1; i < month; ++i) { dayOfYear += length[i]; } return dayOfYear; } // Friend function to compute distance between two dates int distance(const date& d1, const date& d2) { int yearDiff = d1.year - d2.year; int dayDiff = d1.dayOfYear() - d2.dayOfYear(); // Adjust for leap years for (int i = min(d1.year, d2.year); i < max(d1.year, d2.year); ++i) { if (i % 4 == 0 && (i % 100 != 0 || i % 400 == 0)) { yearDiff++; // Add an extra day for each leap year } } return yearDiff * 365 + dayDiff; } // Main function for testing int main() { try { const date independenceDay(7, 4, 1776); independenceDay.print(); cout << " is Independence Day.\n"; // Get today's date const date t; t.print(); cout << " is today.\n"; // Calculate day of the year for Christmas const date xmas(12, 25, 2025); cout << "Christmas is on day " << xmas.dayOfYear() << " of the year.\n"; // Compute distance between dates const date summer(6, 20, 2025); int dist = distance(summer, t); cout << "Only " << dist << " days till summer.\n"; } catch (invalid_argument& e) { cerr << e.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; }