Hi everyone:

I am a c++ newbie. I have created a matrix class based on dynamic arrays. My goal is to use it for creating 2D matrices that I can then use to solve heat/fluid transport problems.

When instantiated, I need each matrix to be initialized with zeroes only. I created a constructor to do this. However, the matrices contain non-zero values. I can't figure out where I'm going wrong, I have realized that I don't really understand constructors, and I would very much appreciate any advice/tips!

I realize that I could probably avoid constructor problems by using vectors from the STL, but I would like to use dynamic arrays.

Below is the code from my header, .cpp, and main files that is relevant to my constructors.

Here's one possibility for the problem that occurred to me... You will see that when I instantiate the matrix class in the main file, I do so like this:

Matrix2d<int> mat;

Maybe by not specifying dimensions upfront, my DEFAULT constructor is invoked. It has rows, cols (the dimensions), and matrix (the object that is instantiated) all set to zero. Could this be a problem? I.e., when I subsequently resize the matrix, it is expanding into territory that has NOT been set to zero by the default constructor (??).

If this sounds like the problem, what should I do? Get rid of the default constructor?

Thanks for any help!

Header file:

```
// Constructors
Matrix2d ();
Matrix2d (int rowsPub, int colsPub);
~Matrix2d();
private:
// Data members
int rows, cols;
T** matrix;
```

From .cpp file:

```
// Constructors
template <typename T>
Matrix2d<T>::Matrix2d()
: rows(0), cols(0), matrix(0) // Default constructor. Creates 1X1 matrix and sets value to 0
{
}
template <typename T>
Matrix2d<T>::Matrix2d(int rowsPub, int colsPub)
: rows(rowsPub), cols(colsPub)
{
rows = rowsPub;
cols = colsPub;
matrix = new T* [ rows ];
for (int i = 0; i < rows; i++)
{
matrix[i] = new T[ cols ];
}
// Initialize
for(int i = 0; i < rows; i++)
for(int j = 0; j < cols; j++)
matrix[i][j] = 0;
}
template <typename T>
Matrix2d<T>::~Matrix2d()
{
for(int i = 0; i < rows; i++)
delete[ ] matrix[i];
delete[ ] matrix;
}
```

In the main file, this is how I create a matrix:

```
Matrix2d<int> mat;
aMat.sizeMatrix2d(xA, yA)
```

*Edited 6 Years Ago by RobBobSmith*: n/a