Sams Teach Yourself C++ in 21 Days

(singke) #1
found in different library packages. For example, a container class library will almost
certainly declare and implement a Listclass. (You’ll learn more about container classes
when you learn about templates on Day 19, “Templates.”)
It is not a surprise to find a Listclass also being used in a windowing library. Suppose
that you want to maintain a list of windows for your application. Further assume that you
are using the Listclass found in the container class library. You declare an instance of
the window library’s Listto hold your windows, and you discover that the member
functions you want to call are not available. The compiler has matched your Listdecla-
ration to the Listcontainer in the Standard Library, but what you really wanted is the
Listfound in the vendor-specific window library.
Namespaces are used to reduce the chance of name conflicts. Namespaces are similar in
some ways to classes, and the syntax is very similar.
Items declared within the namespace are owned by the namespace. All items within a
namespace have public visibility. Namespaces can be nested within other namespaces.
Functions can be defined within the body of the namespace or defined outside the body
of the namespace. If a function is defined outside the body of the namespace, it must be
qualified by the namespace’s name or the calling program must have imported the name-
space into its global namespace.

Resolving Functions and Classes by Name ........................................................


As the compiler parses source code and builds a list of function and variable names, it
also checks for name conflicts. Those conflicts that it can’t resolve are left for the linker
to resolve.
The compiler cannot check for name clashes across object files or other translation units;
that is the purpose of the linker. Thus, the compiler does not even offer a warning in
those cases.
It is not uncommon for the linker to fail with the message
Identifiermultiply defined
where identifieris some named type. You see this linker message if you have defined
the same name with the same scope in different translation units. You get a compiler
error if you redefine a name within a single file having the same scope. Listing 18.1a and
Listing 18.1b are an example, when compiled and linked together, that produces an error
message by the linker.

638 Day 18

Free download pdf