Friendship classes
Mar 12, 2013 at 1:06pm UTC
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.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[40][55];
};
void class_A::create()
{
for (int i=0;i<=39;i++)
{
for (int j=0;j<=54;j++)
{
matrix[i][j]=' ' ;
}
}
}
void class_A::showmtrx()
{
for (int i=0;i<=39;i++)
{
for (int j=0;j<=54;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 24
#include <iostream>
class class_B
{
public :
void init();
void insert();
private :
char obj1;
};
void class_B::init()
{
obj1 = 'A' ;
}
void class_B::insert()
{
class_A ca;
ca.matrix[20][20]=obj1;
}
What i did, i think that classB can access to private members of class A, and it does compile but when i "showmtrx" it seems like the new value of matrix[20][20] doesnt changes, i mean it still showing blank space instead of 'A' char.
What can i do?
thanks
Mar 12, 2013 at 1:18pm UTC
You don't understand the difference between a class and an object of that class.
Or you think that all variables are global.
1 2 3 4 5 6
void class_B::insert()
{
class_A ca; //this is not the object that you created in main()
ca.matrix[20][20]=obj1;
}
Mar 12, 2013 at 1:20pm UTC
Ahh kk, i get it, and how i modify the object i created in "main.cpp" in my classB file?
Is that possible?
Mar 12, 2013 at 1:25pm UTC
Mar 12, 2013 at 1:50pm UTC
so i have to pass an "object" by reference? or a "private member of a class" by reference?
Im trying to google some but im a bit lost,
btw thank u for fast replies man
Topic archived. No new replies allowed.