Cons of using the whole namespace in C++

A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organise code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

Please refer need of namespace in C++ for details.

Suppose we need two header files for a software project :
1: Header1.h
      -namespace one

2: Header2.h
      -namespace two

C++ Code :

Header1.h :

filter_none

edit
close

play_arrow

link
brightness_4
code

namespace one
{
    /*Function to print name of the namespace*/
    void print()
    {
        std :: cout << "This is one" << std :: endl;
    }
}

chevron_right


Header2.h

filter_none

edit
close

play_arrow

link
brightness_4
code

namespace two
{
    /*Function to print name of the namespace*/
    void print()
    {
        std :: cout << "This is two" << std :: endl;
    }
}

chevron_right


Source code file

filter_none

edit
close

play_arrow

link
brightness_4
code

/*Including headers*/
#include <iostream>
#include "Header1.h"
#include "Header2.h"
  
/*Using namespaces*/
using namespace std;
using namespace one;
using namespace two;
  
/*Driver code*/
int main()
{
    /*Ambiguity*/
    print();
}

chevron_right


Output:

Error: Call of overloaded print() is ambiguous.

To overcome this situation, we use namespace objects independently
through scope resolution operator.

Source code file

filter_none

edit
close

play_arrow

link
brightness_4
code

/*Including headers*/
#include <iostream>
#include "Header1.h"
#include "Header2.h"
  
/*Driver code*/
int main()
{
    /*Using function of first header*/
    one :: print();
      
    /*Using function of second function*/
    two :: print();
}

chevron_right


Reference :
http://www.cplusplus.com/forum/beginner/25538/
https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice

Advance sub-domains of namespace :https://www.geeksforgeeks.org/namespace-in-c-set-2-extending-namespace-and-unnamed-namespace/https://www.geeksforgeeks.org/namespace-c-set-3-creating-header-nesting-aliasing-accessing/

GeeksforGeeks Namespace archive

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.