Suppose there is a function called abc() in your code and you are also using some library that has the function with the same name as abc(). Now while executing these functions, the compiler will not know which one to execute among two abs() functions. In such cases namespace comes into action.
A namespace is used to overcome the above situation in a program. It is used as additional information for functions, classes, etc. It allows us to organize the elements of the program into a logical group so that the collision of multiple libraries can be prevented.
Defining a Namespace
The keyword “namespace” is used to define the namespace class and to call prepend (::) the namespace such as:
namespace namespace_name
{
void func() {
// body of function
}
}
//to call, inside main
namespace_name::func();
It could be variable or function in a program.
Example of namespace in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream> using namespace std; namespace space_one { void funcHello() { cout << "Hello space_ONE" << endl; } } namespace space_Two { void funcHello() { cout << "Hello space_Two" << endl; } } int main () { //Calling function with their namespace space_one::funcHello(); space_Two::funcHello(); return 0; } |
Output:
Hello space_ONE
Hello space_Two
C++ program for a namespace with the use of directive.
Here we use using keyword and avoid prepending a namespace.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream> using namespace std; namespace space_one { void funcHello() { cout << "Hello space_ONE" << endl; } } namespace space_Two { void funcHello() { cout << "Hello space_Two" << endl; } } using namespace space_one; int main () { //Calling function with their namespace funcHello(); return 0; } |
Output:
Hello space_ONE