passing a matrix reference to an object

Hello!

I have two classes:

1
2
3
4
5
class class1
{
int **matrix;
int nrow, ncol;
};

and
1
2
3
4
5
6
7
class class2
{
int **matrix;
int nrow, ncol;
public:
void makeSomething();
};


I'd like that the two matrix pointers should be the same. In other words, I'd like to dynamically allocate matrix in either class2 or class1 instances and have the same matrix in both of them.

For example, think class1 as a window and class2 as a dialog. Now the dialog should open a file which stores the matrix data. But the class2's matrix (which is read from a file) whould be then used by the class1 object.

I thought it could be useful the reference (&) type but I don't know how to use it in this case..

thanks
Last edited on
The most simple way would be
1
2
3
4
5
class1 a;
class2 b;
b.matrix = new int*[4];
a.matrix = b.matrix;
do_something_to(a.matrix);//and the changes will be seen on b.matrix too 


If you somehow can't allocate the array in a place visible to both class1 and class2 objects, you'll need another pointer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class class1
{
int ***matrix;
int nrow, ncol;
};
class class2
{
int ***matrix;
int nrow, ncol;
public:
void makeSomething();
};

//...
class1 a;
class2 b;
a.matrix = b.matrix = new int**;
allocate_and_do_something_to(*a.matrix);


You may want to add more structure to your code to make it more simple (for example make a Matrix class). Also, you may want to read http://www.cplusplus.com/forum/articles/17108/
Last edited on
Topic archived. No new replies allowed.