C/C++ >> Friends?
Posted by KaGez on 16:06:00 11-18-2002
Well, up to now I've tried to avoid them, but it looks like now I don't have a choice. Anyways, let's go with the question:

class one
{
public:
friend class two;

private:
int somevar;
}

let's assume I've got class "one" declared as above. How should class "two" look? And, let's say I've initialized something like:

one myclassone;
two myclasstwo;

How can I let class "myclasstwo" access the variable "somevar" of myclassone? I couldn't find anything about this (at least nothing too useful) in my C++ book. So, if you know how to use friends, please tell me. Thx
[addsig]
Posted by dxprog on 00:05:00 11-19-2002
Does it have to be private? THat's the best I can come up with, I've never done classes before. [addsig]
Posted by JWalker on 01:53:00 11-19-2002
Here is a simple example of how friends work:
Code:
#include <iostream>

class one
{
friend class two;
int somevar;
public:
one() // Make sure somevar has a value
: somevar ( 10 )
{}
};

class two
{
public:
void print ( one& myone )
{
std::cout<< myone.somevar <<std::endl;
}
};

int main()
{
one myone;
two mytwo;

mytwo.print ( myone );

return 0;
}

Notice how mytwo.print() has access to myone's private members. For mytwo to access a member of class one, it must have an object of that class to access. If you want class two to have direct access to class one's private members then you need inheritance, not friends.
Posted by KaGez on 20:16:00 11-19-2002
wow, that helped
I've still gotta try some code, but thx for now. Was a really good help
[addsig]