Function/Variable Scope   «Prev  Next»
Lesson 10 Namespaces
Objective Examine the use of namespaces to provide another level of variable scope.

C++ - Namespaces

NameSpace
C++ traditionally had a single, global namespace. Programs written by different people can have name clashes when combined.
Since C++ encourages multivendor library use, the addition of a namespace scope helps programmers avoid name clashes.
Note: The use of namespaces is a relatively new feature of C++ and most older compilers do not support their use. Namespaces are part of the evolving ANSI standard, however, so eventually all compilers will have to support namespace scope.

Code Fragment

In the following code fragment, the program is declaring two namespaces: std, which allows the use of ANSI standard names, and LMPInc, which is a proprietary namespace using names standard to programmers working at LMP Toys Inc.

namespace std {
   #include <iostream.h>
}

namespace LMPInc {
   struct puzzles { .... }
   struct toys { .... }
   .....
}


Namespace Fundamentals

The namespace keyword allows you to partition the global namespace by creating a declarative region. In essence, a namespace defines a scope. The general form of namespace is shown here:
namespace name {
// declarations
}

Anything defined within a namespace statement is within the scope of that namespace.Here is an example of a namespace. It localizes the names used to implement a simple countdown counter class. In the namespace are defined the counter class, which implements the counter, and the variables upperbound and lowerbound, which contain the upper and lower bounds that apply to all counters.
namespace CounterNameSpace {
int upperbound;
int lowerbound;
class counter {
 int count; 
 public:
  counter(int n) {
   if(n <= upperbound) 
     count = n;
   else 
     count = upperbound;
  }
  void reset(int n) {
   if(n <= upperbound) count = n;
  }
  int run() {
   if(count > lowerbound) 
     return count--;
   else 
     return lowerbound;
  }
};
}
Here, upperbound, lowerbound, and the class counter are part of the scope defined by the CounterNameSpace namespace.