Ok, straight to the point.
I have this class :
#ifndef CALENDARIO_H
#define CALENDARIO_H
class Calendario {
public :
Calendario();
Calendario(const int& month, const int& day)
: currentMonth(month), currentDay(day) {};
~Calendario();
// Operator I want to overload
Calendario& operator+(const int&);
// Getters
int getCurrentMonth() const { return currentMonth; }
int getCurrentDay() const { return currentDay; }
// Setters
void setCurrentMonth(int& month) { currentMonth = month; }
void setCurrentDay(int& day) { currentDay = day; }
private :
int currentMonth;
int currentDay;
};
#endif /* CALENDARIO_H */
And the implementation of the function member that is causing me troubles :
Calendario& Calendario::operator+(const int& y) {
if ((y + currentDay) < currentMonth) // With the tests I was doing, at least this if should be executed
currentDay += y;
else if ((y + currentDay) > currentMonth) {
for (int i = 0; i < y; ++i) {
currentDay += 1;
if (currentDay == currentMonth) {
currentDay = 0;
currentMonth += 1;
}
}
}
return *this;
}
and the main :
int main(int argc, char** argv) {
Calendario * cal = new Calendario(10, 5);
//cout << cal->getCurrentDay() << endl; // prints 5
//cout << cal->getCurrentMonth() << endl; // prints 10
Calendario * calsum = cal + 2;
cout << calsum->getCurrentDay(); // prints 0
delete cal;
return 0;
}
For what I understand about overloading operators, that should work, but it doesn't. I'm adding 2 to currentDay of the object cal, and then I'm trying to show it by calling calsum->getCurrentDay(), but it prints 0, and I can't understand why. By overloading the operator+ I'm trying to modify the value of currentDay and currentMonth.
These lines :
Calendario * cal = new Calendario(10, 5); // currentMonth = 10, currentDay = 5
Calendario * calsum = cal + 2; // currentMonth = 10, currentDay = 5 (+2 = 7)
So, I create a Calendario object with the value 10 for currentMonth and 5 for currentDay, then, I'm adding 2 to currentDay (for the code of the overloading operator), later, in the overloading operator :
if ((y + currentDay) < currentMonth) // ( (2 + 5) < 10) = true
currentDay += y; // 5+2 = 7 , now currentDay should be 7
Since y + currentDay (7) are lower than currentMonth (10), the new value of currentDay should be 7. After that, I try to print the new value :
Calendario * calsum = cal + 2;
cout << calsum->getCurrentDay();
but it prints 0, and like I've already said at the beggining... I don't know why...
I think I repeat a lot of things trying to explain my error, but now my head is about to explode .
I hope you can help me, and tell me, if you don't mind, what I'm doing wrong.
I'm reading The C Programming Language by Bjarne Stroustrup, and damn... that's a heavy book for a beginner like me . I'm in the chaper Operator Overloading, and till now, i see that my code should work.
Well... I don't know what else to say... if you need more info, just let me know.
PS : Sorry for my english.
Thanks in advance.