2

I have been told by many programmers that having a using namespace <x> statement in a header file is a bad idea. I have been following this advice blindly till now without understanding why is it so. Now that I am working on a very complex project with lots of namespaces. At times I find it too tempting to tell the compiler about the namespace in the beginning rather than having to type nested ::'s everytime. Example:

ALongNameSpaceName::LongerNamespaceName::BasicUtilityFunctionUsedVeryCommonly

What is the rationale behind this rule? In what scenarios can I ignore this rule?

Yuushi
  • 25,132
  • 7
  • 63
  • 81
bashrc
  • 4,725
  • 1
  • 22
  • 49
  • 2
    You can make use of aliases to shorten the namespace names. http://en.cppreference.com/w/cpp/language/namespace_alias – sajas Jan 29 '14 at 05:43

2 Answers2

6

Because header files get included by other files, you pollute the global namespace of other people who use your code. You may think a little pollution is okay, but if everybody thought that way, we would run out of good names quickly. If you really can't resist using namespace directives in your headers, then limit it to within your header. You can do that by putting the directive inside a scope. For example, if you have your own namespace block, the body of which is entirely restricted to your header file, then you can put a using directive in it without polluting the global namespace.

namespace your_namespace
{
    // this directive is restricted to this namespace block
    using namespace ALongNameSpaceName::LongerNamespaceName;

    ...
}

You can do this inside functions too without worrying about it affecting other code.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
2

Never use using namespace in a header file. This means that anyone that imports your header will have everything from that namespace dumped into their global namespace (unbeknownst to them). This has the potential to cause unexpected name clashes, hard to find/debug errors, and angry programmers out for your blood.

Always use fully qualified names in headers. Within .cpp files, however, you can always shorten the namespace:

namespace ALongNameSpaceName::LongerNamespaceName = ShortNamespace;

ShortNameSpace::BasicUtilityFunction
Yuushi
  • 25,132
  • 7
  • 63
  • 81