class matrix
{
private:
int n;
int** mat;
public:
matrix(int sz);
~matrix();
int*& operator[](int i) { return mat[i]; }
};
matrix::matrix(int sz)
{
n = sz;
mat = newint*[sz];
for(int i = 0; i < sz; i++)
{
mat[i] = newint[sz];
} // end of for
}
matrix::~matrix()
{
for(int i = 0; i < n; i++)
{
delete []mat[i];
} // end of for
delete []mat;
}
1. There are less separate allocations.
2. The actual data of the array is on contiguous memory block, just like it were if it was a plain, statically allocated (2D) array.
The 'mat' in both versions is a pointer to array of sz pointers. Each of those sz pointers do point to somewhere.
PS. In your program, line 9, you do return a reference to a pointer. The caller can thus change the pointer to point elsewhere. Is that intentional and necessary?
PS2. You could overload the operator() to return reference to array element. Yes, syntax would be different, but wouldn't that emphasize that the matrix is an object?