The following line in my code is causing a mysterious segfault:
N = N + M;
Where N and M are objects of the Matrix class:
class Matrix {
vector<int> A;
int m, n;
}
+ operator function:
Matrix Matrix::operator+(const Matrix &other){
//matrices must be of same dimensions
//if not, return null Matrix
if (m != other.m || n != other.n)
return Matrix(0, 0);
Matrix T(m, n);
for (int i = 0; i < m*n; i++){
T.A.at(i) = this->A.at(i) + other.A.at(i);
}
return T;
}
Of course N and M are of the same size (3x3).
The segfault appears even with this:
M = N + M;
or
M = M + N;
or
Matrix P;
P = M + N;
but not with:
Matrix P = M + N;
What could possibly be my mistake? I am new to C++.
EDIT: Here's the = operator:
Matrix Matrix::operator=(const Matrix &other){
A = other.A;
m = other.m, n = other.n;
}
EDIT 2: My constructor can be helpful
Matrix::Matrix(int r, int c):
m(r), n(c), A(r*c)
{ }