avoiding "using namespace std" in header file

Hi guys.

I have somewhere (I really can't remember where) that you should not use the "using namespace std" declaration in the header file. I have several questions about that:

1. What does the namespace means? Is it the list of the keyword that will be used in the program (and are excluded as variable names)?

2. Why should I use that declaration in the header file?

3. What should I do if I need something from the std namespace (vector for example).

Thanks.
Here is a tutorial on namespaces: http://www.cplusplus.com/doc/tutorial/namespaces/

You have several possibilities to access symbols declared inside a namespace:
1
2
3
using namespace std; // everything inside the std namespace is like as if it was in the global one
cout << "blah blah";
vector<int> v(10); 

1
2
3
4
using std::cout;
using std::vector; // as above, restricted to the specified symbols 
cout << "blah blah";
vector<int> v(10); 

1
2
std::cout << "blah blah"; // explicit namespace scope
std::vector<int> v(10); 


You should avoid using namespace std in general because it can cause problems when using different libraries
eg:
1
2
3
4
5
6
7
8
9
// <vector>
namespace std
{
    template < class T, class Allocator = allocator<T> > 
      class vector // STL vector
   {
        // ...
   };
}

1
2
3
4
5
6
// "mylib.h"
template < class T > 
   class vector // my own vector
   {
        // ...
   };

1
2
3
4
5
6
7
8
9
10
11
12
// file.cpp
#include <vector>
#include "mylib.h"

int main()
{
    vecor < int > x; // my own vector ( mylib.h doesn't define any namespace )

    using namespace std;

   vecor < int > y; // which vector? it's ambiguous now that bot vectors can be found in the global namespace
}


You should particularly avoid using in header files as every other file which will #include them will get this issue
1. Just look up namespaces, it's a very simple concept to avoid name clashes between different libraries.
2. You shouldn't.
3. By specifying the full name of the class (std::vector).
yotama9 wrote:
2. Why should I use that declaration in the header file?

Assuming you meant "shouldn't", it's because header files will hide the using directive, bringing the entire namespace into global scope even though you don't see that anywhere in your .cpp file. If it's a commonly used header, that might easily lead to trouble. The most common example is the clash caused by using the identifier "count".

I recommend you avoid using directives; using declarations make a lot more sense, although, personally, I would just rather use the fully qualified name.
Last edited on
Thank you. I'll try to keep that is mind
Topic archived. No new replies allowed.