DoubleOseven
DoubleOseven

Reputation: 271

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;
    }
}

Upvotes: 0

Views: 794

Answers (1)

Donghui Zhang
Donghui Zhang

Reputation: 1133

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.

Upvotes: 2

Related Questions