My question is: Why do the my functions GetNumberOfRows()
and GetNumberOfColumns()
not return the values I specified in my constructor?
I have a class template that allocates memory for Matrix stored as a std::vector
. As private members of this class I have the number of rows and columns (mNumRows
, mNumCols
). I have a constructor that takes number of rows and columns as arguments and creates a std::vector
to store the values in. I have created assertions to make sure that when I index, the matrix, the index must not exceed the number of rows or columns. When overloading the *-operator I assert that matrix columns and vector size are identical (when multiplying my matrix class with a vector class). My program compiles, but during execution of my program I kept getting assertion errors, and I therefore checked the values of mNumRows
and mNumCols
, which proved to be 31, and 0, even though I specified them to be 2 and 2 in the constructor.
My program gives the correct results when specifying mNumRows
and mNumCols
to be a number inside the class, but I want to be able to specify it in my main file. I have provided my header file, where my class is specified.
template<typename T> class Matrix
{
private:
std::vector<T> mData; // entries of matrix
int mNumRows;
int mNumCols; // dimensions
int N;
public:
// copy constructor
Matrix(const Matrix& otherMatrix)
{
mNumRows = otherMatrix.mNumRows;
mNumCols = otherMatrix.mNumCols;
std::vector<T> mData;
for (int i = 0; i < otherMatrix.N; i++)
{
mData = otherMatrix.mData;
}
}
// Storing matrix as a flattened matrix
// And using std::vector
Matrix(int numRows, int numCols)
{
assert(numRows > 0);
assert(numCols > 0);
int mNumRows = numRows;
int mNumCols = numCols;
int N = mNumRows * mNumCols;
for (int i = 0; i < N; i++)
{
mData.push_back(0.0);
}
}
~Matrix()
{
mData.clear();
}
int GetNumberOfRows() const
{
return mNumRows;
}
int GetNumberOfColumns() const
{
return mNumCols;
}
};
In the main file I write.
Matrix mat(2, 2);
std::cout << mat.GetNumberOfRows() << ", " << mat.GetNumberOfColumns() << std::endl;
mat.~Matrix();
The output is 31, 0. It should be 2, 2. Why does the rows and columns change?