[LC++]Is friend our friend?

Carlo Wood carlo at alinoe.com
Mon Sep 3 22:42:15 UTC 2001

On Mon, Sep 03, 2001 at 05:46:36PM +0930, Mark Phillips wrote:
> 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.

I am glad to see someone who is really trying to use C++ object
oriented :).  Concerning the keyword 'friend' I can only give my
own opinion, based on my own experience:  The main reason for
using object orientation is maintainability: When later you (or
someon else) needs to change the code, or add things, then having
designed the code object oriented results in the fact that you
can concentrate on one object at a time and won't be breaking
things because you don't have a complete overview (anymore).
This is also why you can say that object oriented programming
results in better flexibility, and after changing it often over
time, in a higher robustness.
The keyword 'friend' in this context means that, when you are
changing a class A that has class B as friend, then you will have
to understand BOTH classes while changing class A, and probably
will have to change class B as well when making changes to class A.
The only reason to avoid this when possible is that this is
less maintainable (and thus less robust in the end), but I don't
think it is not OO.  I myself use 'friend' whenever the alternative
is to make members public that should really ONLY be accessible to
this friend class.
A special case is the case where two classes form a natural team.
In that case you can decide that they will have to be maintained as
a pair and add mutual friends in order to avoid accessors or in
order to avoid public manipulator methods that are only needed by
the other class.  In this case you should reconsider a different
design when possible, after all you ARE sacraficing maintainability.
There are often alternatives.

Carlo Wood <carlo at alinoe.com>

More information about the tuxCPProgramming mailing list