Here is a matrix template I recently started implementing. It doesn't have many functions since, like I said, I just started it.
Header file:
#ifndef MATRIXX_H
#define MATRIXX_H
#include <iostream>
using namespace std;
template <typename theType> class Matrix
{
public:
Matrix()
{
rows = columns = 0;
matrixRoot = new theType *[rows];
for(int i = 0; i < rows; i++)
{
matrixRoot[i] = new theType[columns];
}
}
Matrix(int rows, int columns)
{
matrixRoot = new theType *[rows];
for(int i = 0; i < rows; i++)
{
matrixRoot[i] = new theType[columns];
}
}
~Matrix()
{
delete [] *matrixRoot;
delete [] matrixRoot;
}
int numrows() const
{
return rows;
}
int numcols() const
{
return columns;
}
private:
int rows;
int columns;
theType **matrixRoot;
};
#endif
The problem arises when I try to run this testing program:
#include "matrixx.h"
#include <iostream>
void TestingMatrix()
{
int r = 5;
int c = 4;
Matrix<int> a(r, c);
cout << "Number of rows: " << a.numrows() << " Number of columns: " << a.numcols() << endl;
}
int main()
{
TestingMatrix();
}
Should it be correct, I'd expect the output to yield something like:
Number of rows: 5 Number of columns: 4
Instead I get something way off:
Number of rows: 134515193 Number of columns: 2515748
It's interesting to note that the number of columns changes but not the rows each time the program is run.
Obviously I won't be able to get anywhere if I can't even initialize an instance of the matrix correctly, so I'd like to know what it is I'm doing wrong that gives me such erroneous results. Btw, I'm aware that my destructor's also messed up since it causes the program to segfault (lol) but that's a problem I plan on addressing on my own in the future. I'd really just appreciate if someone could explain why I'd get those numbers for row and column and how I can get it to return the correct values.
Thank you. (: