Composition Vs. Inheritance
- Inheritance hierarchies model IS-A relationships among
base and derived classes. This is because a derived class object
IS-A type of base class object. For example, a CHECKING ACCOUNT
object (derived class object) IS-A type of ACCOUNT
object (base class object).
- Composite classes, i.e., classes that contain other class
objects as members, model HAS-A relationships. This is because
the container class HAS-Another class as its member component.
For example, an APPOINTMENT object (container class object)
HAS-A DATE object as its member component.
- Both types of relationships may be used to design systems. There are
no well defined criteria for choosing one over the other. The nature of the
application being designed should dictate the choice. In some situations, however,
the choice between Inheritance or Composition is trivial. For example,
in the above mentioned example, to model CHECKING ACCOUNT
as an object that IS-A type of ACCOUNT, makes more
sense than to model CHECKING ACCOUNT as an object that
HAS-An ACCOUNT.
- In addition, to these two types of relationships, there are two other
relationships - USES-A and KNOWS-A. These are also
referred to as Associations. Associations are implemented
in C++ using pointer members or reference members.
Back to Previous Page
Document:
Last Modified On: