[LC++]Is friend our friend?

Mark Phillips mark at austrics.com.au
Mon Sep 3 18:33:48 UTC 2001

I have got the impression, rightly or wrongly, that using the c++
keyword "friend" is frowned upon as "not the object oriented way".
But it would seem to me that, appropriately used, it is a good
and useful mechanism.  I am interested to hear people's opinions.

Presumably the reason "friend" is frowned upon, is that it "breaks"
object information hiding.  Ie, with OO, only public data and 
functions should be available to other objects.  The exception to 
this is when one object is related to another via inheritance.
These objects are able to share non-public information via the
"protected" keyword.  Such overriding of information hiding is
justified on the grounds that they share a special relationship,
because of the inheritance.

My argument though, is that sometimes objects may share a _conceptual_
relationship, even though they are not related via inheritance.
There may be two objects that work together like a team.  They
rely on each other for full functionality to be achieved.  As
such they need each other's private information.  The "friend"
keyword allows this to be achieved.

Is there anything wrong with this argument?  Are there good 
reasons why "friend" should be avoided?  I have heard it said
that "friend" should only be used with legacy code.  Where you
are using an existing code base, friend may be a necessary
evil, but if you're designing something from scratch, you 
should avoid friend, and use a different design strategy.  But
I don't understand why people say this.  I can't see anything
inherently bad about friend.

What if you have two classes which naturally function as a 
team.  Why not connect them via friend?  What is the 
alternative design strategy which is supposedly better?



More information about the tuxCPProgramming mailing list