namespaces - sluczak/cpp_by_example GitHub Wiki
Return to the previous lesson operators
Examples for this part available on git after calling the command:
git checkout -b origin namespaces
In C++ each variable, function and class has its own name. Language semantic rules doesn't allow to have multiple functions of the same name.
Language designers assumed that because of popularity of this language, programmers might suffer from function and class names collision. This is why they created the namespace mechanisms.
A namespace is the subarea of source code where all names has to be unique. Programmer may define several namespaces in order to group associated functions and classes.
Commonly, all external libraries define its own namespaces in order to avoid collisions with programmer's codem just like STL libraries, which shares std
namespace.
The main space is the area which is not defined explicitly as an namespace. The source code below uses the main namespace:
#include <iostream>
int main() {
return 0;
}
In order to create the separated namespace, programmer has to create a namespace
scope and give it a name.
Namespace scope can be defined in any source code file and may surround its whole containings, except the int main()
function, which always has to be located in the main namespace.
In order to call the element of the separated namespace, programmer has to use it as a prefix to the function name, separating the prefix with ::
(two colons).
Below we can see, a differentNamespace
declaration and the differentNamespace::something()
function call.
namespace differentNamespace {
int something() {
std::cout << "some differentNamespace" << std::endl;
return 1;
}
}
int main() {
differentNamespace::something(); //method something() is called with namespace prefix
return 0;
}
In some cases, constant using of prefixes might be cumbersome, because it requires a high redundancy of code.
In such situation programmer may define that he is going to use a concrete namespaces in a particular file.
The definition of using the namespace in some file looks as following:
#include <iostream>
namespace differentNamespace {
int something() {
return 1;
}
}
using namespace differentNamespace;
// now, programmer may use elements from differentNamespace without a prefix
int main() {
something();
return 0;
}
Sometimes it is good enough to declare a usage of separated namespace elements, functions from a namespace. This is done by a function name followed by using
keyword.
#include <iostream>
using std::cout;
int main() {
cout << "hello world" << std::endl;
return 0;
}