#include <iostream>
using namespace std;
class Me {
private: int X;
public:
Me::Me();
void add();
friend class You;
};
class You {
public:
Me m;
void show();
};
Me::Me(){
X = 1;
}
void You::show(){
cout << "The number is " << m.X << endl;
}
void Me::add(){
X+=1;
}
int main(){
Me m;
You y;
y.show();
m.add();
y.show();
system ("pause");}
The output I hoped for was for it to read '1' and then '2', but for some reason the friend class seems to keep the X variable's value at 1, even though I added 1 to it. Please tell me how to fix it, and thanks for your help!
Last edited by MarauderIIC on Sun Oct 28, 2012 5:34 pm, edited 1 time in total.
Reason:I put in the code tags for you. Use them yourself in the future =)
That is because m on Y is declared as a simple member. That makes the m in main and y.m two different objects. If I understand what you're trying to do, you should declare Y::m as a pointer to Me, and then set y's m to be a pointer to main's m.
y.m = &m; // or y.setM(&m), if you like to be an encapsulation nazi
That way, when you call y.show, you print the correct value (of the correct object). Just remember to set it before calling y.show, or you will (hopefully) get a SEGFAULT.
Because main's "Me m" is a totally different variable than "You"'s "Me m". "y" contains its own "Me", so when you declare and call add() on another one inside main(), you're not adding to "y"'s "Me" instance. The only way to do it the way you have written is to put a constructor on You that takes a pointer to a Me instance, change You's "m" variable to a pointer, assign it to the newly declared variable.
/* this only shows changes and is sort of pseudo-code-y because I don't feel like typing*/
class You {
private:
Me* m; /* change to use pointer */
public:
void You(Me* pm) { m = pm; } /* save pointer */
void show() { cout << "The number is " << m->X << endl; } /* change to use pointer */
};
int main() {
Me mainMe;
You y(&mainMe);
y.show();
m.add(); /* this works as you wrote, (but probably isn't what you meant)
because You's Me isn't its own variable, rather, it points to another variable.
In this case, mainMe. So y's "Me" instance is the same as mainMe. */
y.show();
return 0;
}
Further, please don't post duplicate topics. Edit or post inside your existing topic instead. Thanks.
I realized the moment I fell into the fissure that the book would not be destroyed as I had planned.
Thanks to every one who responded, I think i've got it now. And sorry about the duplicate posts, this was my first time posting and I wasn't sure if the post worked the first time.