Class friend, passing private objects

Hello!
im trying to make some friend class but im having some problems, here is my situation.

I've 3 files "main.cpp" "classA.h" "classB.h", this is about showing a matrix of "chars"

This is my "main.cpp"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include "classA.h"
#include "classB.h"
using namespace std;

int main()
{
	class_A ca;
	class_B cb;

	ca.create();
	cb.init();
	cb.insert(ca.matrix);

	ca.showmtrx();	
}


This is my "classA.h"

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>

using namespace std;

class class_A
{
	public:
	   void create();
	   void showmtrx();

	   friend class Class_B;
	   
	private:
	   char matrix[20][20]; 
};


void class_A::create()
{
	for (int i=0;i<=19;i++)
	{
	   for (int j=0;j<=19;j++)
	   {
	      matrix[i][j]=' ';
	   }
	}
}


void class_A::showmtrx()
{
	for (int i=0;i<=19;i++)
	{
	   for (int j=0;j<=19;j++)
	   {
	      cout << matrix[i][j];
	   }
           cout << endl;
	}
}


And this is my "classB.h"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

class class_B
{	
	public:
	   void init();
	   void insert(char (&matrix)[20][20]);
	private:
	   char obj1;

};


void class_B::init()
{
	obj1 = 'A'; 
}

void class_B::insert(char (&matrix)[][])
{
	
	matrix[10][10]=obj1;	
}


What i did, i think that classB can access to private members of class A.
But i get an error that says that matrix[][] its private or sometimes a differente error, my question is how can i correctly pass an object by reference in this case? i've looked up too many different examples but i still cant get it done.

Any help would be appreciated

thanks
cb.insert(ca.matrix);
this code can be written as:
1
2
auto temp = ca.matrix;
cb.insert(temp);

Do you see the problem? You are trying to get access to matrix in main(), not class_B.
Actually you never access anything fromm class_A in your class_B::insert()!

To make use of friendship you can do:
1
2
3
4
5
6
7
8
void class_B::insert(&class_A A)
{
	A.matrix[10][10]=obj1;	//Now you are accessing private member.
}

//...
cb.insert(ca);
//... 


Thanks man, but i still cant do this :(
Last edited on
Topic archived. No new replies allowed.