Peter Hwang
Peter Hwang

Reputation: 991

overloading operator+ for struct without affecting the operands

I would like to overload a plus operator for struct without affecting two operands.

Here is what I have done.

struct Board {   
    int m_len;
    int blk[BLK_MAX][BLK_MAX];
};

Board& operator+(const Board& b1, const Board& b2) {
    Board ret;
    for (int y = 0; y < N; y++) {
        for (int x = 0; x < N; x++) {
            ret.blk[y][x] = b1.blk[y][x] + b2.blk[y][x];
        }
    }
    return ret;
}

It may work fine, however, I don't feel right since the operator returns a local variable. I am not sure if this may cause memory corruption. Is there a better way to do this?

Upvotes: 0

Views: 95

Answers (2)

Light
Light

Reputation: 308

You should NOT return a local variable by reference.

You should just replace:

Board& operator+(const Board& b1, const Board& b2)

by:

Board operator+(const Board& b1, const Board& b2)

Upvotes: 2

Is there a better way to do this?

Sure there is, and it's extremely straightforward. Addition computes a new value. It should therefore return a value (and not a reference):

Board operator+(const Board& b1, const Board& b2) {
    Board ret;
    for (int y = 0; y < N; y++) {
        for (int x = 0; x < N; x++) {
            ret.blk[y][x] = b1.blk[y][x] + b2.blk[y][x];
        }
    }
    return ret;
}

Upvotes: 2

Related Questions