can a friend function work for two classes?

Since a friend function is not a member of a class, can it be used for two classes for performing the same job? I guess no because we've to pass an object of that class in which we're playing.
Two classes can name to same friend, that's no big deal.

The big deal is why are you using friends in the first place.
if same function is to be done in two classes, then it should be better to make a friend function which performs the same task required in both classes.

Two classes can name to same friend, does this have any benefit?
@Rehan FASTian
if same function is to be done in two classes, then it should be better to make a friend function which performs the same task required in both classes.



The same function can not do the same task in two classes in C++ if the classes do not belong to one class hierarchy.
It is possible only when the function deals with two classes simultaneously. In this case it is declared as a friend function for both classes.
The same function can not do the same task in two classes in C++ if the classes do not belong to one class hierarchy.

can't understand "if the classes do not belong to one class hierarchy."
Two classes have different members. So any one function can not do the same task for different classes. It need to have access to members of the both classes simultaneously and explicitly specify their names..
can't understand "if the classes do not belong to one class hierarchy."

We use the term "class hierarchy" to describe a set of classes which inherit from a common base class. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class A
{
  // ...
};

class B: public A
{
  // ...
};

class C: public A
{
  // ...
};

class D: public C
{
  // ...
};

All four of these classes are in the same hierarchy, because they all ultimately inherit from A (except for A itself, which is A :) ).
Last edited on
Thanks everyone!
Topic archived. No new replies allowed.