|

Listing
9.6 shows swap() using pointers, and Listing 9.7
shows it using references. Using the function that
takes references is easier, and the code is easier
to read, but how does the calling function know
if the values are passed by reference or by value?
As a client (or user) of swap(), the programmer
must ensure that swap() will, in fact, change the
parameters.
This
is another use for the function prototype. By examining
the parameters declared in the prototype, which
is typically in a header file along with all the
other prototypes, the programmer knows that the
values passed into swap() are passed by reference,
and thus will be swapped properly.
If
swap() had been a member function of a class, the
class declaration, also available in a header file,
would have supplied this information.
In
C++, clients of classes and functions rely on the
header file to tell all that is needed; it acts
as the interface to the class or function. The actual
implementation is hidden from the client. This allows
the programmer to focus on the problem at hand and
to use the class or function without concern for
how it works.
When
Colonel John Roebling designed the Brooklyn Bridge,
he worried in detail about how the concrete was
poured and how the wire for the bridge was manufactured.
He was intimately involved in the mechanical and
chemical processes required to create his materials.
Today, however, engineers make more efficient use
of their time by using well-understood building
materials, without regard to how their manufacturer
produced them.
It
is the goal of C++ to allow programmers to rely
on well-understood classes and functions without
regard to their internal workings. These "component
parts" can be assembled to produce a program, much
the same way wires, pipes, clamps, and other parts
are assembled to produce buildings and bridges.
In
much the same way that an engineer examines the
spec sheet for a pipe to determine its load-bearing
capacity, volume, fitting size, and so forth, a
C++ programmer reads the interface of a function
or class to determine what services it provides,
what parameters it takes, and what values it returns.
|