I am trying to overload the operator= for matrices. I have an error when I run the code but cannot figure out what it is: *** glibc detected *** ./class_matrix.o: double free or corruption (fasttop):
The code is the following:
template <typename T>
class Matrix{
private:
T* mat;
int rows;
int cols;
int sz;
void initMat( int rows, int cols ){
if( rows <= 0 || cols <= 0 ){
mat = NULL;
return;
}
this->rows = rows;
this->cols = cols;
sz = rows * cols;
mat = new T[sz];
}
public:
// Constructors
Matrix(){
mat = NULL;
}
Matrix( int rows, int cols ){
initMat( rows, cols );
}
Matrix( int rows, int cols, T initVal ){
initMat( rows, cols );
for( int i=0; i<sz; i++ )
mat[i] = initVal;
} // End constructors
// Destructor
~Matrix(){
delete [] mat;
} // End destructor
// Function to access values in the matrix
T& operator()( int row, int col ) const{
return mat[ cols * row + col ];
} // End of the function
inline Matrix& operator=( const Matrix& other ) const{
for( int i=0; i<other.sz; i++ ) {
mat[i] = other.mat[i];
}
return *this;
};
// Function to add two matrices
Matrix operator+( const Matrix& other ) const{
Matrix neo(other.rows, other.cols);
for( int i=0; i<sz; i++ ) neo.mat[i] = mat[i] + other.mat[i];
return neo;
}; // End of the function
};
I am pretty sure it is a pointer error.
Thanks