FAQ 19.08 What does it mean that friendship isn t transitive?

FAQ 19.08 What does it mean that friendship isn't transitive?

A friend of a friend isn't (necessarily) a friend.

Friendship is personal; it is explicitly granted to a particular, named individual. All friends of a class are declared explicitly in the body of the class. This clearly identifies the entities that need to be updated when the private: part of a class is changed.

In the following code, operator<< is a friend of BinaryTree, which is a friend of BinaryTreeNode, but this does not make operator<< a friend of BinaryTreeNode.

 #include <iostream> using namespace std; class BinaryTreeNode;                                <-- 1 class BinaryTree { public:   friend ostream& operator<< (ostream&, const BinaryTree&) throw();                                                      <-- 2 protected:   BinaryTreeNode* root_; }; class BinaryTreeNode { public:   // Public interface for BinaryTreeNode goes here private:   friend BinaryTree;                                 <-- 3   BinaryTreeNode* left_;   BinaryTreeNode* right_; }; ostream& operator<< (ostream& ostr, const BinaryTree& bt) throw() {   // This code can access bt.root_ (it's a friend of BinaryTree),   // but not bt.root_->left_ (it's not a friend of BinaryTreeNode).   return ostr; } 

(1) Predeclare class BinaryTreeNode

(2) operator<< can access BinaryTree

(3) BinaryTree can access BinaryTreeNode

If operator<< needs to access BinaryTreeNode::left_ or BinaryTreeNode::right_, it must be made a friend of BinaryTreeNode as well:

 class BinaryTreeNode { public:   // Public interface for BinaryTreeNode goes here private:   friend BinaryTree;                                 <-- 1   friend ostream& operator<< (ostream&, const BinaryTree&) throw();                                                      <-- 2   BinaryTreeNode* left_;   BinaryTreeNode* right_; }; 

(1) BinaryTree can access BinaryTreeNode

(2) operator<< can access BinaryTreeNode

Note that the compiler doesn't care where a friend declaration appears within a class, so the placement is normally done to make the code easily readable by other programmers (see FAQ 19.12). In the example, normal users might be somewhat confused by the friendship relationship between BinaryTreeNode and operator<<, so it has been moved out of the public: section (the public: section is where normal users look to find out how to use a class).



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net