2 dimensional array in classes

I need to create a matrix class of 2D array....is the following code correct

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include "matrix.h"

using namespace std;

Matrix::Matrix()
{//allocating memory
	array2D= new int*[rows];
  for (int i = 0; i < rows; ++i)
    array2D[i] = new int[cols];
 }

Matrix::~Matrix()
{//deleteing memory to prevent memory leak
  for (int i = 0; i < rows; ++i)
   delete [] array2D[i];

  delete [] array2D;
 } 

Matrix::Matrix( const Matrix & M)
{
//copy constructor
	array2D = M.array2D;
}
No this code is not correct. The problem is in the copy constructor

1
2
3
4
5
Matrix::Matrix( const Matrix & M)
{
//copy constructor
	array2D = M.array2D;
} 


if you build an object from other object and the last one will be deleted then the first object will use already unallocated memory because its pointer points to the same memory as the pointer of the deleted object.

In the copy constructor you shall allocated ne memory and copy there the original object. The same is valid for the copy assignment operator but it also requires to delete its currrent matrix.
Last edited on
Topic archived. No new replies allowed.