a namespace is something which is used to help limit scope.
Let's say if I have a function:
1 2 3 4
|
void print(char* msg)
{
std::cout << msg;
}
|
And then I want to add another version of the function:
1 2 3 4
|
void print(char* msg)
{
std::cout << "The message is: " << msg;
}
|
You can't have two versions of the same function. But we CAN use namespaces:
1 2 3 4 5 6 7 8
|
namespace n1
{
void print(char* msg);
}
namespace n2
{
void print(char* msg);
}
|
Now we can select which one we want with:
1 2
|
n1::print("Hello");
n2::print("Hello again");
|
If there is one that we
always want to use, we can do this:
1 2
|
using namespace n1;
print("This uses the print function from n1");
|
This becomes particularly useful when you have a few large libraries that you are trying to bring in. If each one uses their own namespace, there will be no clashes. If they do not use namespaces, then if two share a same function name, you'll get errors.
Things in the standard library (cout, string, endl) are in the std:: namespace. This will let you make your own
class string
or
class cout
and there will be no conflict.
Note that if you use:
using namespace std;
then you bring in everything from the std:: namespace. This is not limited to just things that you use so it can get dangerous because you are bringing in hundreds of classes and functions. To limit the number of objects you are bringing in, try:
using std::cout;
This will bring in only std::cout.