While reading from Bruce Eckel's "Thinking in C++" about namespaces, I encountered the following statement:
However you'll virtually never see a using directive in a header file (at least not outside of scope). The reason is that using directive eliminate the protection of that particular namespace, and the effect last until the end of current compilation unit. If you put a using directive (outside of a scope) in a header file, it means that this loss of "namespace protection" will occur within any file that include this header, which often mean other header files.
Would you please like to help me to comprehend the above statement with some easy example?
Consider this program:
If you try to compile it, you'll see errors:
The problem here is that when
main()
specifiesstring x;
, the compiler's not sure whether the user-defined::string
or includedstd::string
is wanted.Now imagine you take the top part of the program... lines 1 through 5 - up to and including the
struct string
... and put it into a header file which you then#include
beforemain()
. Nothing changes: you still have an error. So, just as for standalone programs, header files withusing
statements in them can cause trouble for other code that includes them, making some of their statements ambiguous.It can be a bigger pain though, as headers can be included - directly or indirectly - by arbitrarily huge amounts of dependent code, and...
using
statement from the header, or<string>
, or any other header affectingstd::
...might break code including the problematic header. Either problem may render dependent code uncompilable, and issues may not even be noticed until another compilation is attempted. Further, the person suffering due to the
using
statement may not have filesystem/code-repository permissions, corporate authority etc. to remove theusing
statement from the header, nor fix other affected client code.That said, if a header only has "using" inside a class or function, then there's no affect on code beyond that scope, so the potential impact of changes to std:: is dramatically reduced.