DoubleOseven DoubleOseven - 1 month ago 23
C++ Question

Matrix class in c++ assignment operator

I am trying to implement a Matrix class in c++. I am having problems trying to get the assignment operator to work. At this point I am lost. The issue is that I am getting an error saying that "vector subscript is out of range". If I take this code away

this->size = A.size;
from the assignment overloading operator the compiler doesn't complain. The assignment operator is supposed to return a reference to the Matrix object. I tried creating a new Matrix object but that gave me the same error. Any hints?

**Matrix.hpp**

class Matrix
{
private:
int size; //size of matrix
double value;
std::vector<double> M;
public:
...
}

**Header.cpp**

Matrix& Matrix::operator=(const Matrix& A)
{
if (this == &A)
{
return *this;
}
else
{
this->size = A.size; // this is causing problems
return *this;
}
}

Answer

When you assign one matrix to another, you not only need to change the size data member, but also need to change the other data members such as resizing the vector of doubles.

Comments