Sams Teach Yourself C++ in 21 Days

(singke) #1
the aggregated object. Aggregation is simpler to use than inheritance, and should be used
when possible.
You also saw how to declare both friend classes and friend functions. Using a friend
function, you saw how to overload the extraction operator, to allow your new classes to
use coutthe same as the built-in classes do.
Remember that public inheritance expresses is-a, aggregation expresses has-a, and pri-
vate inheritance expresses implemented in terms of. The relationship delegates-tocan be
expressed using either aggregation or private inheritance, although aggregation is more
common.

Q&A ....................................................................................................................


Q Why is it so important to distinguish between is-a,has-a, and implemented in
terms of?
A The point of C++ is to implement well-designed, object-oriented programs.
Keeping these relationships straight helps to ensure that your design corresponds to
the reality of what you are modeling. Furthermore, a well-understood design will
more likely be reflected in well-designed code.
Q What is containment?
A Containment is another word for aggregation.
Q Why is aggregation preferred over private inheritance?
A The challenge in modern programming is to cope with complexity. The more you
can use objects as black boxes, the fewer details you have to worry about and the
more complexity you can manage. Aggregated classes hide their details; private
inheritance exposes the implementation details. To some extent, this is also true for
conventional public inheritance, which is sometimes used when aggregation would
be a better solution.
Q Why not make all classes friends of all the classes they use?
A Making one class a friend of another exposes the implementation details and
reduces encapsulation. The idea is to keep as many of the details of each class hid-
den from all other classes as possible.
Q If a function is overloaded, do I need to declare each form of the function to
be a friend?
A Yes, if you overload a function and declare it to be a friend of another class, you
must declare a friend for each form to which you want to grant this access.

590 Day 16

Free download pdf