Write a Date class that validates day/month/year (including leap years), and a member function that returns the next day; test month and year boundaries.
#include <format>
#include <iostream>
#include <stdexcept>
#include <string>
class Date {
int d_, m_, y_;
static bool leap(int y) { return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0; }
static int days_in(int m, int y) {
static constexpr int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
return m == 2 && leap(y) ? 29 : days[m - 1];
}
public:
Date(int d, int m, int y) : d_(d), m_(m), y_(y) {
if (m < 1 || m > 12 || d < 1 || d > days_in(m, y)) throw std::invalid_argument("invalid date");
}
Date next() const {
int d = d_ + 1, m = m_, y = y_;
if (d > days_in(m, y)) { d = 1; if (++m > 12) { m = 1; ++y; } }
return {d, m, y};
}
std::string str() const { return std::format("{:02}-{:02}-{}", d_, m_, y_); }
};
int main() {
for (Date dt : {Date(28, 2, 2024), Date(28, 2, 2026), Date(31, 12, 2026), Date(30, 4, 2026)})
std::cout << dt.str() << " -> " << dt.next().str() << '\n';
try { Date bad(29, 2, 2026); } catch (const std::exception& e) { std::cout << e.what() << '\n'; }
return 0;
}
28-02-2024 -> 29-02-2024 28-02-2026 -> 01-03-2026 31-12-2026 -> 01-01-2027 30-04-2026 -> 01-05-2026 invalid date
Private static helpers hold the calendar rules; the constructor refuses invalid dates, so next() can rely on a valid starting point.