Sams Teach Yourself C++ in 21 Days

(singke) #1
Creating and Using Namespaces 649

18


namespace Window
{
int value1 = 20 ;
int value2 = 40 ;
}


...
Window::value1 = 10 ;


using namespace Window ;
value2 = 30 ;


The scope of the usingdirective begins at its declaration and continues on to the end of
the current scope. Notice that value1must be qualified to reference it. The variable
value2does not require the qualification because the directive introduces all names in a
namespace into the current scope.


The usingdirective can be used at any level of scope. This enables you to use the direc-
tive within block scope; when that block goes out of scope, so do all the names within
the namespace. The following example shows this behavior:


namespace Window
{
int value1 = 20 ;
int value2 = 40 ;
}
//...
void f()
{
{
using namespace Window ;
value2 = 30 ;
}
value2 = 20 ; //error!
}


The final line of code in f(),value2 = 20 ;is an error because value2is not defined.
The name is accessible in the previous block because the directive pulls the name into
that block. When that block goes out of scope, so do the names in namespace Window.
For value2to work in the final line, you need to fully qualify it:


Window::value2 = 20 ;

Variable names declared within a local scope hide any namespace names introduced in
that scope. This behavior is similar to how a local variable hides a global variable. Even
if you introduce a namespace after a local variable, that local variable hides the name-
space name. Consider the following example:


namespace Window
{

Free download pdf