This Class Relationships Study Guide pulls together, in one place, the resources we use in CSE687 - Object Oriented Design
to discuss class relationships.
Class Relationships - Presentatons and Diagrams
Class Relationships
The Four Class Relationships:
An instance of a C++ class can have any of four relationships with other classes:
Inheritance:
Models an "is-a" relationship, e.g., the derived class is a specialization of its base class. For example,
both Generals and Privates are specializations of the soldier class. They both salute, but in different ways.
Inheritance supports both substitution and code reuse. A pointer or reference to any derived class may be
assigned to a pointer or reference of its base type. That means that a client can declare a base pointer and use it
to hold a pointer to a derived object delivered by some function without ever knowing the exact type of the object.
Composition:
A C++ class can declare an instance of some type as a member. That creates a strong ownership. The composed instance
is created at the same time as the composer. It is an irrevocable part of the composer.
Aggregation:
If a C++ class declares a pointer to some type as a member or local to some member function, that pointer may, at any time,
be attached to an instance of the pointed to type on the C++ heap by calling new.
This must be done in some member function, and so the aggregating
class will only own an instance of the aggregated type if that function is called. So aggregation is a weaker form of
ownership - it does not guarantee that the aggregated possess that part.
Using:
If a member function of a C++ class is passed a pointer or reference to an existing instance of another type we say that
an instance of the class is using the instance of the referenced type. It does not own the instance and should not destroy
it when finished as the instance belongs to some other entity in the program's code.
Example Class and Object Relationships
An Example of the class relationships and corresponding object layout in memory:
The top half of the second figure shows an example set of classes and their relationships. All of the four relationships are shown in
a plausible configuration.
In the bottom half instances of each of the classes are shown with their layout in memory. Member functions are shown as the
thin rectangles on the top of each object. Note that the base and derived objects share the public member functions of the base.
More details are provided in the presentation and code example linked below.
Hierarchy Presentation,
Example code
Presentation and code with details about complete set of class relationships: inheritance, composition, aggregation, using.