hi im trying to make a matrix class which makes use of operator overloading. Ive followed several tutorials, and the one which looked best implemented the binary operators (+ - etc) using unary operators (+=) as such.

Code:

#include "Matrix.h"
Matrix::Matrix(int m, int n, float* values)
{
nn = n;
mm = m;
matrix = new float[mm*nn];
for(int mi = 0; mi < mm; mi++)
{
for(int ni = 0; ni < nn; ni++)
{
matrix[mi*nn+ni] = values[mi*nn+ni];
}
}
}
Matrix::Matrix()
{
nn = 1;
mm = 1;
matrix = new float[1];
matrix[0] = 0;
}
Matrix& Matrix::operator=(const Matrix &m2)
{
if(&m2 != this)
{
nn = m2.nn;
mm = m2.mm;
delete[] matrix;
matrix = new float[mm*nn];
for(int mi = 0; mi < mm; mi++)
{
for(int ni = 0; ni < nn; ni++)
{
matrix[mi*nn+ni] = m2.matrix[mi*nn + ni];
}
}
}
return *this;
}
const Matrix& Matrix::operator+=(const Matrix &m2)
{
for(int mi = 0; mi < mm; mi++)
{
for(int ni = 0; ni < nn; ni++)
{
matrix[mi*nn+ni] += m2.matrix[mi*nn + ni];
}
}
wxString output;
output.Printf(_T("%f %f\n%f %f"), matrix[0], matrix[1], matrix[2], matrix[3]);
wxMessageBox(output);
return *this;
}
const Matrix& Matrix::operator+(const Matrix &m2)
{
Matrix result = *this;
result += m2;
return result;
}

the problem is in these examples result is created on the stack (i assume) and i get warning messages whenever i compile. the obvious solution would be to return a Matrix on the heap and write another constructor which accepts a Matrix pointer assign it to itself using the = operator, but this seems messy. whats the standard approach to this problem

thx