namespace

From Appmethod Topics
Jump to: navigation, search

Go Up to Keywords, Alphabetical Listing Index


Category

C++ Specific Keywords

Description

Most real-world applications consist of more than one source file. The files can be authored and maintained by more than one developer. Eventually, the separate files are organized and linked to produce the final application. Traditionally, the file organization requires that all names that aren't encapsulated within a defined namespace (such as function or class body, or translation unit) must share the same global namespace. Therefore, multiple definitions of names discovered while linking separate modules require some way to distinguish each name. The solution to the problem of name clashes in the global scope is provided by the C++ namespace mechanism.

The namespace mechanism allows an application to be partitioned into a number of subsystems. Each subsystem can define and operate within its own scope. Each developer is free to introduce whatever identifiers are convenient within a subsystem without worrying about whether such identifiers are being used by someone else. The subsystem scope is known throughout the application by a unique identifier.

To use a namespace:

  • Define a namespace with the keyword namespace and write the inner code.
  • Access the symbols from the defined namespace with the keyword using or by specifying the namespace with the scope resolution operator.
Example:
struct A { void foo(); }; // #1
struct B { void foo(); }; // #2
struct C : A, B  {
  void callfoo() {
      foo(); //error:  ambiguous
      B::foo(); // picks #2
    }
};

See also