FAQ 37.03 What is the syntax and semantics for private and protected inheritance?

The following example shows a simple has-a relationship between a car object and its engine object; it uses normal composition, where the Engine member object appears in the private: section of the Car class.

 class Engine { public:   void publ() throw(); protected:   void prot() throw(); }; class CarA { public:   // ... private:   Engine e_; }; 

Obviously composition does not create an is-a relationship: a CarA is not a kind-of an Engine. In particular, users cannot legally convert a CarA* to an Engine*. Also note that a CarA object contains exactly one Engine object (though it could be made to contain more than one).

Private inheritance accomplishes essentially the same thing. In the following example, CarB is said to privately inherit from Engine (if the symbols : private Engine are changed to : protected Engine, CarB is said to protectedly inherit from Engine).

 class CarB : private Engine { public:   // ... }; 

Just as with normal composition, there is no is-a relationship: a CarB is not a kind-of Engine. In particular, normal (nonfriend) users cannot legally convert a CarB* to an Engine*. Also like normal composition, a CarB object contains exactly one Engine object (however, unlike normal composition, private and protected inheritance does not allow a second Engine subobject to appear as a second private and/or protected base class).

The main difference between composition and private/protected inheritance is access to the protected members of Engine. With private/protected inheritance, members and friends of CarB can access the protected: members of Engine (in this case, they can access both Engine::publ() and Engine::prot()). However, with normal composition, members and friends of CarA can only access Engine::publ(); they are forbidden to access Engine::prot(). The usual reason people use private/protected inheritance is for this additional access authority; but note that the extra authority carries with it extra responsibility.

Another difference between composition and private/protected inheritance is the ability to convert a CarB* to an Engine*. With private/protected inheritance, members and friends of CarB can convert a CarB* to an Engine*. With normal composition this is not possible: no one can legally convert a CarA* to an Engine*.

There are several caveats when using private/protected inheritance. Simple composition (has-a) is needed if it is necessary to contain several member objects of the same class; private or protected inheritance can introduce unnecessary multiple inheritance.



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