Namespaces provide a way of declaring variables within a program that have similar names.
It allows users to define functions with the same name as a function in a pre-defined library or used-defined functions within main()
.
Namespaces can also be used to define classes, variable names, and functions.
The following code shows how namespaces can be declared.
n_name
is the name of the namespacefoo
is the function namenamespace n_name{//enter code herevoid foo(){cout << "This is a user-defined function"<<endl;}}
Once the namespace is declared, the scope resolution operator (::) can be used to refer to variables within the namespace.
The following example shows how to refer to the function foo
defined in the namespace n_name
above.
n_name::foo()
The following code shows a complete example of how to declare the namespace and uses its functions within a program that contains similar functions.
#include <iostream>using namespace std;namespace n_name{// namespace declaredint x= 100; // variable x within namespacevoid foo() // function foo within namespace{//prints the value of x defined within namespacecout<< "The value of x in namespace is: "<< x <<endl;}}void foo(int x) //function declared{//prints the value of x passed within parameterscout<< "The value of x in main is: " << x << endl;}int main() {// declare variable xint x = 10;foo(x); //call function foon_name:: foo(); //call function foo defined in namespacereturn 0;}
You can also direct the program to use the assigned namespace as default by making use of the using keyword.
Free Resources