CrimOudin
CrimOudin

Reputation: 5

Operator+ not returning what i expect c++

matrixType& matrixType::operator+(const matrixType& matrixRight)
{
    matrixType temp;
    if(rowSize == matrixRight.rowSize && columnSize == matrixRight.columnSize)
    {
        temp.setRowsColumns(rowSize, columnSize);
        for (int i=0;i<rowSize;i++)
        {
            for (int j=0;j<columnSize;j++)
            {   
                temp.matrix[i][j] = matrix[i][j] + matrixRight.matrix[i][j];
            }
        }
    }
    else
    {
        cout << "Cannot add matricies that are different sizes." << endl;
    }
    cout << temp;
    return temp;
}


the cout at the end prints out what i would expect but when i add matrix a and matrix b together in my main there is no output i don't understand why it would be right on the line before i return it but it doesn't do anything when it returns.

int main()
{
    matrixType a(2,2);
    matrixType b(2,2);
    matrixType c;
    cout << "fill matrix a:"<< endl;;
    a.fillMatrix();
    cout << "fill matrix b:"<< endl;;
    b.fillMatrix();

    cout << a;
    cout << b;

    cout <<"matrix a + matrix b =" << a+b;

    system("PAUSE");
    return 0;
}

the cout a prints out the matrix a correct and same for b but the a+b doesnt print anything although in the operator overload above i print it out and it prints out correct.

Upvotes: 0

Views: 71

Answers (1)

juanchopanza
juanchopanza

Reputation: 227390

You are returning a reference to a temporary, leading to undefined behaviour. An operator+ should return a value:

matrixType operator+(const matrixType& matrixRight);

Upvotes: 2

Related Questions