0

I overwrote a + operator:

Matrix& Matrix::operator+(Matrix m1)
{
    //This should never be triggered
    if(this->data.capacity() != m1.data.capacity() || this->data[0].capacity() != m1.data[0].capacity())
    {
        cout << "Dimensions don't match, can't add.\n";
        throw 7;
    }
    vector<vector<double>> result;
    result.resize(m1.data.capacity());
    for(int i = 0; i < m1.data.size(); i++)
    {
        result[i].resize(m1.data[0].size());
        for(int j = 0; j < m1.data[0].size(); j++)
        {
            result[i][j] = m1.data[i][j] + this->data[i][j];
        }
    }
    return Matrix(m1.getRows(),m1.getCols(), result);
}

This is the corresponding Constructor:

Matrix::Matrix(int rows, int cols, vector<vector<double>> data)
{
    this->rows = rows;
    this->cols = cols;
    this->data = data;
}

Here's the executing code:

c = (a+b);

When I assign a breakpoint at the last line of the operator overload, I can see the correct results in result and both cols and rows are assigned correctly. When I step out, c has "rows" and "cols" set correctly, but data is empty. Why is that?

Dennis Röttger
  • 1,975
  • 6
  • 32
  • 51
  • [See this answer](http://stackoverflow.com/a/6445794/583833) on why you shouldn't return a reference or pointer to a function's local variable. – Borgleader Feb 21 '14 at 17:24
  • You are returninh a reference to a function's local object. That is never a good thing to do. – ach Feb 21 '14 at 17:24
  • Also, you should be passing the Matrix by reference or const reference (preferably const reference), not by value. `operator + (Matrix& m1)` – PaulMcKenzie Feb 21 '14 at 17:26

1 Answers1

5

Your operator + is wrong. It should be returning a new object, not a reference to a local object (which is UB anyway).

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45