Need of namespace:
- As the same name can’t be given to multiple variables, functions, classes, etc. in the same scope.
- So to overcome this situation namespace is introduced.
Below is the C++ program illustrating the use of namespace with the same name of function and variables:
2 This is fun() of n1 5 This is fun() of n2
- In the above example program, both n1 and n2 have a variable and function of the same name x and fun() respectively.
- The namespace is used to decrease or limit the scope of any variable or function.
- As in the above code variable x and method fun() were limited to namespaces n1 and n2. Thus, their scope was not outside the n1 or n2.
- Every time using the scope resolution operator (::) in a variable or a function defined is not required, it can be solved with “using” directive.
- The using directive means to include the whole code written in the namespace in the closing scope.
Below is the C++ program demonstrating the use of the “using” directive:
2 This is fun() of n1
- In the above program, after writing “using namespace n1“, there is no need to use the scope resolution for utilizing the members of n1.
- It can be interpreted as “using” copies of the code written in the namespace to the scope in which it has been written.
If “using namespace n1” is written inside the main() and tries to use the members (fun() and x in this case) in the different functions it would give a compile-time error.
Below is the C++ program illustrating the use of “using namespace” inside main() function:
- It is known that “std” (abbreviation for the standard) is a namespace whose members are used in the program.
- So the members of the “std” namespace are cout, cin, endl, etc.
- This namespace is present in the iostream.h header file.
- Below is the code snippet in C++ showing content written inside iostream.h:
- Now when cout<<“GeeksforGeeks”; is written, the compiler searches for cout in our program which is kept in the std namespace, so the instruction given to the compiler that if the compiler doesn’t find anything in the current scope, try finding it in the std namespace.
- It is not necessary to write namespaced, simply use scope resolution (::) every time uses the members of std. For example, std::cout, std::cin, std::endl etc.
Below is the C++ program illustrating the use of std:
The value of x is 10
Explanation: The output of the program will be the same whether write “using namespace std” or use the scope resolution.