Advanced Inheritance 571
16
Adding Friend Classes ........................................................................................
Sometimes, you will create classes together, as a set. For example,PartNodeand
PartsListwere tightly coupled, and it would have been convenient if PartsListcould
have read PartNode’s Partpointer,itsPart, directly.
You wouldn’t want to make itsPartpublic, or even protected, because this is an imple-
mentation detail of PartNodeand you want to keep it private. You do want to expose it to
PartsList,however.
If you want to expose your private member data or functions to another class, you must
declare that class to be a friend. This extends the interface of your class to include the
friend class.
After a class declares another to be its friend, all of the declaring classes’ member data
and functions are public to the friend class. For example, if PartsNodedeclares
PartsListto be a friend, all PartsNode’s member data and functions are public as far as
PartsListis concerned.
It is important to note that friendship cannot be transferred. Although you are my friend
and Joe is your friend, that doesn’t mean Joe is my friend. Friendship is not inherited,
either. Again, although you are my friend and I’m willing to share my secrets with you,
that doesn’t mean I’m willing to share my secrets with your children.
Finally, friendship is not commutative. Assigning Class One to be a friend of Class Two
does not make Class Two a friend of Class One. You might be willing to tell me your
secrets, but that doesn’t mean I am willing to tell you mine.
DOinherit publicly when the derived
object is a kind of the base class.
DOuse aggregation when you want to
delegate functionality to another class,
but you don’t need access to its pro-
tected members.
DOuse private inheritance when you
need to implement one class in terms of
another, and you need access to the base
class’s protected members.
DON’Tuse private inheritance when you
need to use more than one instance of
the base class. You must use aggrega-
tion. For example, if PartsCatalog
needed two PartsLists, you could not
have used private inheritance.
DON’Tuse public inheritance when
members of the base class should not be
available to clients of the derived class.
DO DON’T