0

I have written a Date class and Im trying to practice operator overloading on this class. I have tried to overload the operator++ to increment the day by one, but i still get this error: cannot increment value of type 'Date'! here is my method for overloading this operator:

Date Date::operator++()
{
  day++;
  if (day > days_of_month(month, year)) {
    day = 1;
    month++;
    if (month > 12) {
      month = 1;
      year++;
    }
  }
  return *this;
}

and this is the days_of_month method:

int days_of_month(int m, int y)
{
  if (m < 7)
    return 31;
  else if (m < 12)
    return 30;
  else if (m == 12)
    return is_leap_year(y) ? 30 : 29;
  else
    abort();
}
Max Langhof
  • 23,383
  • 5
  • 39
  • 72
shirazy
  • 109
  • 3
  • 11
  • 1
    *Where* do you get the error? Can you please create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) to show us, with the location of the error marked with e.g. a comment? Also please copy-paste the *full* and *complete* error into the question, including any possible informational notes. – Some programmer dude May 08 '18 at 12:20
  • 1
    By the way, that's a very weird definition of the number of days per month. What calendar are you using? – Some programmer dude May 08 '18 at 12:22
  • @Someprogrammerdude when in main function I use Date d(30, 10, 1397); and then d++ . I get this error: cannot increment value of type 'Date' . its the exact error message I get and I use solar based calender. – shirazy May 08 '18 at 12:27
  • 1
    Oh you mean [the Solar Hijri calendar](https://en.wikipedia.org/wiki/Solar_Hijri_calendar)? – Some programmer dude May 08 '18 at 12:33
  • @Someprogrammerdude yes I mean this one ;) – shirazy May 08 '18 at 12:34
  • Possible duplicate of [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – Richard Critten May 08 '18 at 12:40

1 Answers1

6

There are two types of incrementation - post-increment and pre-increment. What you've overloaded is the latter and you're trying to use the former.

Usually you provide the two for a class. It looks like this:

Date& Date::operator++() // for ++d
Date Date::operator++(int) // for d++
DeiDei
  • 10,205
  • 6
  • 55
  • 80