Namespaces
Chapter 7
What does this statement, using namespace std;
do and what similar statements can we use? Find out here!
Problems with conflicting global identifiers (constants, functions, enum
types, etc.):
Global identifiers in a header file used in a program become global in the program
- A syntax error occurs if an identifier has the same name as a global identifier in the header file
The same problem can occur with third-party libraries
- Common solution: third-party vendors begin their global identifiers with
_
(underscore)
Do not begin identifiers in your program with_
- Common solution: third-party vendors begin their global identifiers with
Namespaces attempt to solve these problems.
- A namespace includes members, which have a scope that is local to the namespace.
Syntax to create a namespace:
namespace NamespaceName // NamespaceName can be any identifier you want
{
// Put here: variable declarations, named constants, functions,
// or another namespace
const int MAX_SIZE = 100; // Example Constant
int calculateSize(); // Example function prototype; definitions go
// below the namespace (and below main)
} // <-- No semicolon here
int NamespaceName::calculateSize() // Example function definition
{
// ...
}
A namespace member can be accessed outside the namespace:
cppNamespaceName::identifier;
Or the identifier can be used without specifying the namespace if you use:
cppusing namespace NamespaceName;
Or for just the specific identifier.
cppusing NamespaceName::MAX_SIZE;
After the using statement, it is NOT necessary to put the
NamespaceName::
before the namespace member.
Unless a namespace member and a global identifier or a block identifier have the same name.Example for defining a function with a prototype in a namespace (below main).
(See the example ofcalculateSize()
above).