Is it possible to make two member functions of two classes each other's friend?

Hi, all:
I am troubled by the following problem. Suppose I have two classes X, Y both have a private part. Then X::f and Y::g are two member functions of X and Y respectively. I want X::f to have access to Y's private and Y::g have access to X's by granting friendship. However it seems this is not allowed.

For example, if I want X::f be a friend to Y, I must define (not only declare) X before Y, so that Y knows f is a part of X, vice versa, I need Y to be defined before X to make Y::g a friend of X. But these two contradict each other.

Any ideas? Many thanks.
Check this out:

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
using namespace std;

class A;
class B;

class C
{
    friend class A;
    friend class B;

    A & a;
    B & b;

    C(A & a_, B & b_):a(a_),b(b_) {}

    void f();
    void g();
};

class A
{
    friend class C;
    int data;

public:
    void f(B & b) { C(*this,b).f(); }
};

class B
{
    friend class C;
    int data;

public:
    void g(A & a) { C(a,*this).g(); }
};

void C::f()
{
    cout << "f(" << &a << ',' << &b << ")" << endl;
    b.data=1234;
    cout << "b.data=" << b.data << endl;
}

void C::g()
{
    cout << "g(" << &a << ',' << &b << ")" << endl;
    a.data=4321;
    cout << "a.data=" << a.data << endl;
}

int main()
{
    A a;
    B b;

    a.f(b);
    b.g(a);

    cout << "\nhit enter to quit...";
    cin.get();
    return 0;
}

EDIT: Also, check this out -> http://en.wikipedia.org/wiki/Fundamental_theorem_of_software_engineering ;)
Last edited on
Thank you so much! That's indeed enlightening!
Topic archived. No new replies allowed.