Can a friend function work for two classes?

If yes then how?
You mean if a function can be a friend of two classes? For that you just need to put the friend declaration in both classes.

1
2
3
4
5
6
7
8
9
class A
{
	friend void foo();
};

class B
{
	friend void foo();
};
closed account (zb0S216C)
I believe so:

1
2
3
4
5
6
7
8
9
10
11
class Class_A
  {
    public:
      friend void Function( Class_A & );
  };

class Class_B
  {
    public:
      friend void Function( Class_B & );
  };

A "friend" function declaration needs to refer to an object of the class of which it is a friend.

Wazzak
In case of Peter, what can be done using this function? This particular function seems to be useless.

In case of Framework, two functions definitions will be given, actually this is not one function, rather two functions (overloaded) are being used.

My question remains unanswered.
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
#include <iostream>

struct B ;

struct A
{
    A( int i ) : v(i) {}

    private : int v ;

    friend int operator+ ( const A& a, const B& b ) ;
};

struct B
{
    B( int i ) : v(i*i) {}

    private : int v ;

    friend int operator+ ( const A& a, const B& b ) ;
};

inline int operator+ ( const A& a, const B& b ) { return a.v + b.v ; }
//inline int operator+ ( const B& b, const A& a ) { return a+b ; }

int main()
{
    A seven(7) ;
    B sixteen(4) ;
    std::cout << seven+sixteen << '\n' ; // 23
}
Why not use inheritance?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
class Common
{
    int member;
    friend void Foo(Common& input);
};

class A : public Common {};
class B : public Common {};

void Foo (Common& input)
{
    std::cout << input.member;
}

int main()
{
    A a;
    B b;
    Foo (a);
    Foo (b);
    return 0;
}
OR another example:
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
#include <iostream>
class Common
{
public:
    Common(int i) : member(i) {}
protected:
    int member;
    friend std::ostream& operator<<(std::ostream& o, Common& rhs);
};

class A : public Common { public: A() : Common(1) {}};
class B : public Common { public: B() : Common(2) {}};

std::ostream& operator<<(std::ostream& o, Common& rhs)
{
    o << rhs.member;
    return o;
}

int main()
{
    A a;
    B b;
    std::cout << a;
    std::cout << b;
    return 0;
}
Topic archived. No new replies allowed.