Namespaces
Namespaces
void seriousCalcs()
{
using namespace geo;
//other code here
double c = circumf(r); //OK
}
double c = circumf(r); //not OK
Here the members of the namespace are visible only within the function
body.
Namespaces in Header Files
• Namespaces are most commonly used in
header files containing library classes or
functions.
• Each such library can have its own namespace.
• By this time you are familiar with the
namespace std, whose members constitute
the Standard C++ Library.
Multiple Namespace Definitions
• There can be several instances of the same namespace definition:
namespace geo
{
const double PI = 3.14159;
} // end namespace geo
//(some other code here)
namespace geo
{
double circumf(double radius)
{ return 2 * PI * radius; }
} //end namespace geo
• This looks like a redefinition, but it’s really just a continuation of the
same definition.
• It allows a namespace to be used in several header files, which can
then all be included in a source file.
Example
In the Standard C++ Library, dozens of header files use the namespace std.
//fileA.h
namespace alpha
{
void funcA();
}
//fileB.h
namespace alpha
{
void funcB();
}
fileMain.cpp
#include “fileA.h”
#include “fileB.h”
using namespace alpha;
funcA();
funcB();
Declarations Outside a namespace
• You can place declarations outside a namespace
that behave as if they were inside it.
• All you need is the scope resolution operator and
the namespace name:
namespace beta
{
int uno;
}
int beta::dos;
• Here, both uno and dos are declared in the
namespace beta.
Unnamed Namespaces
• You can create a namespace without a name.
• Doing so creates a namespace that is
automatically visible throughout the file in which
it’s defined, but not visible from other files.
• The compiler gives an unnamed namespace an
internal name unique to the file.
• Elements declared in the unnamed namespace
can be accessed from anywhere in the file.
• In the following listing, funcA() and funcB() can
access the gloVar variable in their respective files.
Example
//fileA.cpp
namespace //unnamed namespace unique to fileA.cpp
{
int gloVar = 111;
}
funcA()
{ cout << gloVar; } //displays 111
//fileB.cpp
namespace //unnamed namespace unique to fileB.cpp
{
int gloVar = 222;
}
funcB()
{ cout << gloVar; } //displays 222
• In this example both files contain a variable named gloVar, but there’s no conflict
because each variables is declared in an unnamed namespace unique to its file
and is invisible everywhere else.
• This approach provides an alternative to the use of static for restricting the scope
of global variables to their own file. In fact, the namespace approach is now
considered preferable to making elements static.