Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading the += operator [duplicate]

I have the following code to overload the + and += operators respectively for the class Date. The operator + was successfully overloaded, and it will take an integer n and increase Date objects by n days. This is done by applying the next_day function n times.

inline Date operator+(Date d, int n)
{
    for(char j=1; j<=n; j++){
        d=d.next_day(d);
    }
    return d;
}
inline Date operator+=(Date d, int n)
{
    Date p=d+n;
    return p;
}

Having overloaded the + operator, I'm using it to define the overloading of += as well. But although no errors occurred in compilation, when I use the overloaded += it doesn't seem to have any effect.

Here's my main.cpp:

#include <iostream>
#include "Date.h"
using namespace std;

int main() {

Date Initialday = Date (12,1,2012);

Initialday+=1;
cout <<"Next day = "<< Initialday <<endl;

return 0;
}

Running the main function still gives me 12/1/2012 instead of 12/2/2012. What am I doing wrong? Note: I've already overloaded << to output Date objects in a readable format, so I don't think that's the issue.

like image 240
Patrick Jane Avatar asked Oct 29 '25 08:10

Patrick Jane


1 Answers

The simple fix is to take your Date object in by reference, modify it, and return it by reference. That's the expected behavior of operator+=.

inline Date& operator+=(Date &d, int n)
{
    d = d + n;
    return d;
}

However, to implement operator+= in terms of operator+ is backwards. It should be the other way around. operator+= should act on the members of the object, changing them directly. Then operator+ should be implemented in terms of that:

inline Date& operator+=(Date& lhs, int rhs)
{
    ... // code here to modify lhs directly

    return lhs;
}

inline Date operator+(Date lhs, int rhs)
{
    return lhs += rhs;
}
like image 80
Benjamin Lindley Avatar answered Oct 31 '25 21:10

Benjamin Lindley