Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can two classes friend each other?

Tags:

c++

I haven't yet worked out a specific case. But I am about to embark on writing some code that I feel will end up needing this; and so I wanted to know if:

  1. Two classes can friend each other; so that they can freely access the private and protected members of the other (I believe the answer is yes, and ofcourse I can simply try it out!). Any detailed references or other question links with answers are also very welcome. I am aware of forward declarations and include guard compiler pre-directives and their use. My questions are rather more related to the semantics of the C++ language in terms of what it can offer with regard to this possibility of mutual friendship and how to use it properly.
  2. Is this generally recommended? Do people employ this kind of design on a regular basis? Under what circumstances would this be a recommended design (preferably with some examples).
like image 387
squashed.bugaboo Avatar asked Mar 06 '11 05:03

squashed.bugaboo


1 Answers

You can have mutual friendship:

class A {
    friend class B;
};

class B {
    friend class A;
};

Whether or not this makes sense depends entirely on the problem you are trying to solve. It definitely could make sense in certain circumstances.

The only example from my current project that utilizes mutual friendship is a container implementation: the container class is a friend of its iterator class and vice versa.

like image 96
James McNellis Avatar answered Oct 06 '22 17:10

James McNellis