I am working with a dateType class and need to make a function to show next day and the previous day. I have my function set using const keyword so that it can't be changed by users, but now I can't increase my day. help???

int dateType::nextDay() const
{
getDay();
dDay++;
return dDay;
}
int dateType::previousDay() const
{
getDay();
dDay--;
return dDay;
}

Dani AI

Generated

: the core issue is that a member declared const promises not to change the object's observable state. That prevents updating dDay inside that function. noticed the const/immutability angle and was right to ask for the full class — whether to change the qualifier depends on your design goals.

Practical options (pick one):

  • Make the mutating functions non-const and update the members in place. This is the usual approach when nextDay()/previousDay() change the object.
  • Keep const and return a new dateType representing the next/previous day (functional style).
  • Use mutable for intentionally cache-like members (not recommended for normal date fields).
  • Implement operator++/operator-- (prefix modifies & returns reference; postfix returns old value).

Example helpers and an in-place increment/decrement (note: signatures must be non-const if they modify members):

bool isLeap(int y) {
    return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}

int daysInMonth(int y, int m) {
    static const int mdays[] = {31,28,31,30,31,30,31,31,30,31,30,31};
    if (m == 2 && isLeap(y)) return 29;
    return mdays[m - 1];
}

dateType& dateType::nextDay() {
    ++day;
    if (day > daysInMonth(year, month)) {
        day = 1;
        if (++month > 12) { month = 1; ++year; }
    }
    return *this;
}

dateType& dateType::previousDay() {
    if (--day < 1) {
        if (--month < 1) { month = 12; --year; }
        day = daysInMonth(year, month);
    }
    return *this;
}

Debug checklist: ensure members are signed (avoid unsigned underflow), validate initial date, test month/year boundaries (Feb 28/29, Dec 31 -> Jan 1), and decide whether callers expect an in-place change or a new object. For detail on const semantics see . If using modern C++, consider C++20 calendar types like std::chrono::year_month_day for robust date handling. Post the full class definition if more tailored fixes are needed.

Recommended Answers

All 2 Replies

Please use code tags to post your code. Enclose your code in code tags.
Also post your entire code so that we can be in a state of answering your questions, dont post half baked snippets.

Functions can't be edited by users anyway. When a function is const, it means that function can't change anything outside of it, which in your case is dDay. Get rid of the const and it'll work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.