FAQ 19.09 What does it mean that friendship isn t inherited?

FAQ 19.09 What does it mean that friendship isn't inherited?

Just because someone trusts you does not automatically mean they will trust your children.

Suppose class Fred grants friendship privileges to another class Base and class Derived is derived from class Base. Derived does not automatically have friendship privileges to access the innards of Fred just because its base class is a friend of Fred. This rule improves encapsulation. Without this rule, anyone could automatically gain friendship (and access to internals) by deriving from a known friend.

 class Base; class Fred {   friend Base; }; class Base {   //Member functions of Base are friends of Fred }; class Derived : public Base {   //Member functions of Derived are not friends of Fred }; 

In the following example, an EggCarton is not supposed to have more than a dozen eggs (numEggs_ <= 12). Class EggCartonFiller is trusted not to violate the semantics of an EggCarton, so EggCarton makes EggCartonFiller a friend. This friendship allows EggCartonFiller::addAnEgg() to access EggCarton::numEggs_.

 class EggCartonFiller;   // Tell the compiler that                          //     "EggCartonFiller" is a class class EggCarton { public:   EggCarton() throw();   // Creates an empty carton private:   friend EggCartonFiller;   int numEggs_;          // numEggs_ can't exceed a dozen }; EggCarton::EggCarton() : numEggs_(0) { } class EggCartonFiller { public:   void addAnEgg(EggCarton& carton) throw(); }; void EggCartonFiller::addAnEgg(EggCarton& carton) throw() {   if (carton.numEggs_ < 12)     ++ carton.numEggs_; } 

If friendship were inherited, anyone could create a class derived from EggCartonFiller and possibly violate the semantics of an EggCarton.

 class SubversiveFiller : public EggCartonFiller { public:   void violateEncapsulation(EggCarton& carton) throw(); }; void SubversiveFiller::violateEncapsulation(EggCarton& carton) throw() {   #ifdef GENERATE_ERROR     carton.numEggs_ = 13;                            <-- 1   #endif } 

(1) Compile-time error: Can't access carton.numEggs_



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