Back to Item 27: Explicitly disallow use of implicitly generated member functions you don't want.
Continue to Classes and Functions: Implementation

Item 28: Partition the global namespace.

The biggest problem with the global scope is that there's only one of them. In a large software project, there is usually a bevy of people putting names in this singular scope, and invariably this leads to name conflicts. For example, `library1.h` might define a number of constants, including the following:

    const double LIB_VERSION = 1.204;

Ditto for `library2.h`:

    const int LIB_VERSION = 3;

It doesn't take great insight to see that there is going to be a problem if a program tries to include both `library1.h` and `library2.h`. Unfortunately, outside of cursing under your breath, sending hate mail to the library authors, and editing the header files until the name conflicts are eliminated, there is little you can do about this kind of problem.

You can, however, take pity on the poor souls who'll have your libraries foisted on them. You probably already prepend some hopefully-unique prefix to each of your global symbols, but surely you must admit that the resulting identifiers are less than pleasing to gaze upon.

A better solution is to use a C++ `namespace`. Boiled down to its essence, a `namespace` is just a fancy way of letting you use the prefixes you know and love without making people look at them all the time. So instead of this,

    const double sdmBOOK_VERSION = 2.0;      // in this library,
                                             // each symbol begins
    class sdmHandle { ... };                 // with "sdm"

    sdmHandle& sdmGetHandle();             // see Item 47 for why you
                                           // might want to declare
                                           // a function like this

you write this:

    namespace sdm {
      const double BOOK_VERSION = 2.0;
      class Handle { ... };
      Handle& getHandle();
    }

Clients then access symbols in your namespace in any of the usual three ways: by importing all the symbols in a namespace into a scope, by importing individual symbols into a scope, or by explicitly qualifying a symbol for one-time use. Here are some examples:

    void f1()
    {
      using namespace sdm;           // make all symbols in sdm
                                     // available w/o qualification
                                     // in this scope

      cout << BOOK_VERSION;          // okay, resolves to
                                     // sdm::BOOK_VERSION
      ...

      Handle h = getHandle();        // okay, Handle resolves to
                                     // sdm::Handle, getHandle
      ...                            // resolves to sdm::getHandle

    }

    void f2()
    {
      using sdm::BOOK_VERSION;        // make only BOOK_VERSION
                                      // available w/o qualification
                                      // in this scope

      cout << BOOK_VERSION;           // okay, resolves to
                                      // sdm::BOOK_VERSION
      ...

      Handle h = getHandle();         // error! neither Handle
                                      // nor getHandle were
      ...                             // imported into this scope

    }

    void f3()
    {
      cout << sdm::BOOK_VERSION;      // okay, makes BOOK_VERSION
                                      // available for this one use
      ...                             // only

      double d = BOOK_VERSION;        // error! BOOK_VERSION is
                                      // not in scope

      Handle h = getHandle();         // error! neither Handle
                                      // nor getHandle were
      ...                             // imported into this scope

    }

(Some namespaces have no names. Such unnamed namespaces are used to limit the visibility of the elements inside the namespace. For details, see Item M31.)

One of the nicest things about namespaces is that potential ambiguity is not an error (see Item 26). As a result, you can import the same symbol from more than one namespace, yet still live a carefree life (provided you never actually use the symbol). For instance, if, in addition to namespace `sdm`, you had need to make use of this namespace,

    namespace AcmeWindowSystem {

      ...

      typedef int Handle;

      ...

    }

you could use both `sdm` and `AcmeWindowSystem` without conflict, provided you never referenced the symbol `Handle`. If you did refer to it, you'd have to explicitly say which namespace's `Handle` you wanted:

    void f()
    {
      using namespace sdm;                 // import sdm symbols
      using namespace AcmeWindowSystem;    // import Acme symbols

      ...                                  // freely refer to sdm
                                           // and Acme symbols
                                           // other than Handle

      Handle h;                            // error! which Handle?

      sdm::Handle h1;                      // fine, no ambiguity

      AcmeWindowSystem::Handle h2;         // also no ambiguity

      ...

    }

Contrast this with the conventional header-file-based approach, where the mere inclusion of both `sdm.h` and `acme.h` would cause compilers to complain about multiple definitions of the symbol `Handle`.

Namespaces were added to C++ relatively late in the standardization game, so perhaps you think they're not that important and you can live without them. You can't. You can't, because almost everything in the standard library (see Item 49) lives inside the namespace `std`. That may strike you as a minor detail, but it affects you in a very direct manner: it's why C++ now sports funny-looking extensionless header names like `<iostream>`, `<string>`, etc. For details, turn to Item 49.

Because namespaces were introduced comparatively recently, your compilers might not yet support them. If that's the case, there's still no reason to pollute the global namespace, because you can approximate `namespace`s with `struct`s. You do it by creating a struct to hold your global names, then putting your global names inside this struct as static members:

    // definition of a struct emulating a namespace
    struct sdm {
      static const double BOOK_VERSION;
      class Handle { ... };
      static Handle& getHandle();
    };

    const double sdm::BOOK_VERSION = 2.0;      // obligatory defn
                                               // of static data
                                               // member

Now when people want to access your global names, they simply prefix them with the struct name:

    void f()
    {
      cout << sdm::BOOK_VERSION;

      ...

      sdm::Handle h = sdm::getHandle();

      ...
    }

If there are no name conflicts at the global level, clients of your library may find it cumbersome to use the fully qualified names. Fortunately, there is a way you can let them have their scopes and ignore them, too.

For your type names, provide typedefs that remove the need for explicit scoping. That is, for a type name `T` in your namespace-like struct `S`, provide a (global) typedef such that `T` is a synonym for `S::T`:

    typedef sdm::Handle Handle;

For each (static) object `X` in your struct, provide a (global) reference `X` that is initialized with `S::X`:

    const double& BOOK_VERSION = sdm::BOOK_VERSION;

Frankly, after you've read Item 47, the thought of defining a non-local static object like `BOOK_VERSION` will probably make you queasy. (You'll want to replace such objects with the functions described in Item 47.)

Functions are treated much like objects, but even though it's legal to define references to functions, future maintainers of your code will dislike you a lot less if you employ pointers to functions instead:

    sdm::Handle& (* const getHandle)() =      // getHandle is a
      sdm::getHandle;                         // const pointer (see
                                              // Item 21) to
                                              // sdm::getHandle

Note that `getHandle` is a const pointer. You don't really want to let clients make it point to something other than `sdm::getHandle`, do you?

(If you're dying to know how to define a reference to a function, this should revitalize you:

    sdm::Handle& (&getHandle)() =      // getHandle is a reference
      sdm::getHandle;                  // to sdm::getHandle

Personally, I think this is kind of cool, but there's a reason you've probably never seen this before. Except for how they're initialized, references to functions and const pointers to functions behave identically, and pointers to functions are much more readily understood.)

Given these typedefs and references, clients not suffering from global name conflicts can just use the unqualified type and object names, while clients who do have conflicts can ignore the typedef and reference definitions and use fully qualified names. It's unlikely that all your clients will want to use the shorthand names, so you should be sure to put the typedefs and references in a different header file from the one containing your `namespace`-emulating struct.

`struct`s are a nice approximation to `namespace`s, but they're a long trek from the real thing. They fall short in a variety of ways, one of the most obvious of which is their treatment of operators. Simply put, operators defined as `static` member functions of structs can be invoked only through a function call, never via the natural infix syntax that operators are designed to support:

    // define a namespace-emulating struct containing
    // types and functions for Widgets. Widget objects
    // support addition via operator+
    struct widgets {
      class Widget { ... };

      // see Item 21 for why the return value is const
      static const Widget operator+(const Widget& lhs,
                                    const Widget& rhs);

      ...

    };

    // attempt to set up global (unqualified) names for
    // Widget and operator+ as described above

    typedef widgets::Widget Widget;

    const Widget (* const operator+)(const Widget&,        // error!
                                     const Widget&);       // operator+
                                                           // can't be a
                                                           // pointer name

    Widget w1, w2, sum;

    sum = w1 + w2;                           // error! no operator+
                                             // taking Widgets is
                                             // declared at this
                                             // scope

    sum = widgets::operator+(w1, w2);        // legal, but hardly
                                             // "natural" syntax

Such limitations should spur you to adopt real namespaces as soon as your compilers make it practical.

Back to Item 27: Explicitly disallow use of implicitly generated member functions you don't want.
Continue to Classes and Functions: Implementation