FAQ 15.02 What is a namespace?

graphics/new_icon.gif

A namespace is a declarative region that can be used to package names, improve program readability, and reduce name clashes in the global namespace. It is an elegant alternative to using prefixes to indicate the sources of names.

At the most basic level, the syntax for namespaces is shown in the following example.

 namespace MySubsystem {   class Fred {                                       <-- 1     // ...   };   class Wilma {                                      <-- 2     // ...   };   void funct()                                       <-- 3   {     // ...   }   // Other declarations for MySubsystem go in here } 

(1) Class MySubsystem::Fred

(2) Class MySubsystem::Wilma

(3) Function MySubsystem::funct()

Namespaces facilitate building large systems by partitioning names into logical groupings.

Namespaces are "open" and can be added to at different places. For most situations, this incremental approach is probably a better alternative than trying to specify all of the names in one location, and this approach is used heavily in the standard library. However the incremental approach must be used carefully, because the effect is as if the compiler made a single pass and knew about only the names that were part of the namespace the last time the namespace was explicitly introduced into the source file.

Namespaces can be nested if desired. Java has a concept similar to namespaces called packages.

UML expresses namespaces as shown below (they are called packages in UML):

graphics/15fig01.gif



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net