Question

I'm having trouble with overloading the post increment method.
My pre increment is fine.
I also have pre/post decrements, and they both work perfectly.
The increment and decrement body should be similar. The only difference should be ++/--, but I'm not sure why my post increment won't work like my post decrement.

pre increment

upDate upDate::operator++() {
   int julian = convertDateToJulian(datePtr[0], datePtr[1], datePtr[2]);
   julian++;
   convertDateToGregorian(julian);
   return (*this);
}

post increment

upDate upDate::operator++(int num) {
   upDate temp (*this);
   int julian = convertDateToJulian(datePtr[0], datePtr[1], datePtr[2]);
   julian++;
   convertDateToGregorian(julian);
   return temp;
} 

post decrement

upDate upDate::operator--(int num) {
   upDate temp(*this);
   int julian = convertDateToJulian(datePtr[0], datePtr[1], datePtr[2]);
   julian--;
   convertDateToGregorian(julian);
   return temp;
}

This is my main:

upDate d5(11, 10, 2004);
++d5;
cout << d5 << endl;
cout << "Expected November 11, 2004\n" << endl;

//not working
upDate d6(11, 11, 2004);
d5++;
cout << d6 << endl;
cout << "Expected November 12, 2004\n" << endl;

upDate d11(12, 3, 1992);
d11--;
cout << d11 << endl;
cout << "Expected: December 2, 1992\n" << endl;

The output is:
//the date was originally Nov 10 2004
//++incr
November 11, 2004
Expected: November 11, 2004

//the date was originally Nov 11 2004
//incr++
November 11, 2004 //output should not be this
Expected: November 12, 2004

//the date was originally Dec 2 1992
//decr--
December 1, 1992
Expected: December 1, 1992

Was it helpful?

Solution

There is a typo in your main:

//not working
upDate d6(11, 11, 2004);
d6++;  // <---- you have d5++;
cout << d6 << endl;
cout << "Expected November 12, 2004\n" << endl;

OTHER TIPS

You have a typo. In this code snippet

//not working
upDate d6(11, 11, 2004);
d5++;
cout << d6 << endl;
cout << "Expected November 12, 2004\n" << endl;

you applied the post increment operator to d5

d5++;

but outputed d6

cout << d6 << endl;

d6 was not changed.

Also take into account that the correct declaration of the pre-increment operator is

upDate & upDate::operator++();

that is the operator should return lvalue. while your operator returns a temporary object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top