Sams Teach Yourself C++ in 21 Days

(singke) #1
Advanced Inheritance 553

16


You could create a new PartsCatalogclass and have it contain a PartsList. The
PartsCatalogcould delegate management of the linked list to its aggregated PartsList
object.
An alternative would be to make the PartsCatalogderive from PartsListand, thereby,
inherit the properties of a PartsList. Remembering, however, that public inheritance
provides an is-arelationship, you should ask whether a PartsCatalogreally is a type of
PartsList.
One way to answer the question of whether PartsCatalogis a PartsListis to assume
that PartsListis the base and PartsCatalogis the derived class, and then to ask these
other questions:


  1. Is anything in the base class that should not be in the derived? For example, does
    the PartsListbase class have functions that are inappropriate for the
    PartsCatalogclass? If so, you probably don’t want public inheritance.

  2. Might the class you are creating have more than one of the base? For example,
    might a PartsCatalogneed two PartsListsto do its job? If it might, you almost
    certainly want to use aggregation.

  3. Do you need to inherit from the base class so that you can take advantage of virtual
    functions or access protected members? If so, you must use inheritance, public or
    private.
    Based on the answers to these questions, you must choose between public inheritance
    (the is-arelationship) and either private inheritance (explained later today) or aggregation
    (the has-arelationship).


Terminology
Several terms are being used here. The following helps to summarize these key terms:



  • Aggregation—Declaring an object as a member of another class contained by that class.
    This is also referred to as has-a.

  • Delegation—Using the members of an aggregated class to perform functions for the
    containing class.

  • Implemented in terms of—Building one class on the capabilities of another without using
    public inheritance (for instance, by using protected or private inheritance).


Using Delegation ............................................................................................


Why not derive PartsCatalogfrom PartsList? The PartsCatalogisn’t a PartsList
because PartsLists are ordered collections, and each member of the collection can
Free download pdf