C++ Programming

From Wikibooks, open books for an open world
Jump to navigation Jump to search

The namespace keyword allows you to create a new scope. The name is optional, and can be omitted to create an unnamed namespace. Once you create a namespace, you'll have to refer to it explicitly or use the using keyword. A namespace is defined with a namespace block.

    namespace name {

In many programming languages, a namespace is a context for identifiers. C++ can handle multiple namespaces within the language. By using namespace (or the using namespace keyword), one is offered a clean way to aggregate code under a shared label, so as to prevent naming collisions or just to ease recall and use of very specific scopes. There are other "name spaces" besides "namespaces"; this can be confusing.

Name spaces (note the space there), as we will see, go beyond the concept of scope by providing an easy way to differentiate what is being called/used. As we will see, classes are also name spaces, but they are not namespaces.

Use namespace only for convenience or real need, like aggregation of related code, do not use it in a way to make code overcomplicated for you and others

namespace foo {
  int bar;

Within this block, identifiers can be used exactly as they are declared. Outside of this block, the namespace specifier must be prefixed (that is, it must be qualified). For example, outside of namespace foo, bar must be written foo::bar.

C++ includes another construct which makes this verbosity unnecessary. By adding the line using namespace foo; to a piece of code, the prefix foo:: is no longer needed.

unnamed namespace[edit | edit source]

A namespace without a name is called an unnamed namespace. For such a namespace, a unique name will be generated for each translation unit. It is not possible to apply the using keyword to unnamed namespaces, so an unnamed namespace works as if the using keyword has been applied to it.

    namespace {
namespace alias[edit | edit source]

You can create new names (aliases) for namespaces, including nested namespaces.

   namespace identifier = namespace-specifier;