LearnFrenzy
Sign in Take a free test

Classes and Objects · Class Programs · Question 1

Date class with validation and next day in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

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.

Solution
main.cpp
#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;
}

Output Verified by compiling and running

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.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links