"friendship" question

T

Thomas

hi all,

I have 2 classes, A and B. Each class has a member function that needs to
access an element of the other class. Here's the code:

#include <iostream>
using namespace std;

class B;

class A
{ public:
void AFunction(B& arg_b);
friend void B::BFunction(B&); //allow BFunction to access avar
private:
int avar;
};

class B
{ public:
void BFunction(A& arg_a);
friend void A::AFunction(B&); //allow AFunction to access bvar
private:
int bvar;
};

void A::AFunction(B& arg_b) { cout << arg_b.bvar << endl; }
void B::BFunction(A& arg_a) { cout << arg_a.avar << endl; }

int main()
{ A MyAObject;
B MyBObject;
}

This doesn't compile because B::BFunction(B&) is declared a friend before B
is defined. But swapping classes A and B just makes A::AFunction the
problem...

Is there a way to do this without making the whole classes friends of each
other?

Thanks in advance,

Thomas
 
R

red floyd

Thomas said:
hi all,

I have 2 classes, A and B. Each class has a member function that needs to
access an element of the other class. Here's the code:

#include <iostream>
using namespace std;

class B;

class A
{ public:
void AFunction(B& arg_b);
friend void B::BFunction(B&); //allow BFunction to access avar
private:
int avar;
};

class B
{ public:
void BFunction(A& arg_a);
friend void A::AFunction(B&); //allow AFunction to access bvar
private:
int bvar;
};

void A::AFunction(B& arg_b) { cout << arg_b.bvar << endl; }
void B::BFunction(A& arg_a) { cout << arg_a.avar << endl; }

int main()
{ A MyAObject;
B MyBObject;
}

This doesn't compile because B::BFunction(B&) is declared a friend before B
is defined. But swapping classes A and B just makes A::AFunction the
problem...

Is there a way to do this without making the whole classes friends of each
other?

You're pretty much toast. However, either CUJ or DDJ had an article on
"attorney" classes, which basically functioned as friend proxies.
 
T

Thomas

am Freitag, 14. April 2006 20:06 schrieb red floyd:
Thomas wrote:
[snipped]


You're pretty much toast. However, either CUJ or DDJ had an article on
"attorney" classes, which basically functioned as friend proxies.

ok thanks, I'll play around with these.
BTW. please excuse my poor english, but what's the meaning of "You're pretty
much toast" ?? My dictionary's explanation of "toast" doesn't seem to make
sense here...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,076
Latest member
OrderKetoBeez

Latest Threads

Top