I was reading a document on operator overloading: http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html however when I run the code below (in an actual context) I always get a warning on how result is a local variable. And it makes sense that I shouldn’t be returning a local variable, but it seems to work fine. Is there a way to eliminate the warning with code like the following:
const Matrix & Matrix::operator+(const Matrix &other) const
{
Matrix result(*this);
result += other;
return result;
}
The example on caltech’s website like this, is on the bottom of the link
To remove the warning, you need to return the
Matrixby value.You should also ideally define it as a free function since semantically it should not need to modify the object it is called on.