Game Development Reference
In-Depth Information
Creating Namespaces
Namespaces allow us to group functionality from multiple files into a single named code unit. This
allows us to keep our functions and data types together. It also has the added benefit of keeping our
new type and function names out of the
global namespace
. Usually we can only use a function name
a single time, so by using namespaces we can use the same function and type names in a different
context. Listing 7-4 shows an example that creates and uses two different namespaces.
Listing 7-4. Creating Namespaces
#include "stdafx.h"
#include <iostream>
namespace Player
{
void PrintName()
{
std::cout << "My name is Bruce!" << endl;
}
}
namespace Vehicle
{
void PrintName()
{
std::cout << "I am a car!" << endl;
}
}
using namespace Player;
int _tmain(int argc, _TCHAR* argv[])
{
PrintName();
Vehicle::PrintName();
return 0;
}
This example shows the creation of two different namespaces, one named
Player
and another
named
Vehicle
. Both of these namespaces contain a function named
PrintName
. If these were not
contained within a namespace they would be required to have different names. Because they are
contained within namespaces their usage in the code must be
qualified
. We can qualify our use of
items contained in namespaces in two ways.
The first example is the
Player
namespace. We use the
using namespace
directive to inform all of the
following code that any type and function within the namespace can be used. You can see this in the
first line of the
_tmain
function, which can call
PrintName
directly.