Let’s say I declare a class string
myself. Because I’m a lazy bum, I do so in global namespace.
// Solar's stuff
class string
{
public:
string();
// ...
};
Some time later on, I realize that re-using some of your code would benefit my project. Thanks to you making it Open Source, I can do so:
#include <solarstuff.hpp>
#include <phoenixstuff.hpp>
string foo;
But suddenly the compiler doesn’t like me anymore. Because there is a ::string
(my class) and another ::string
(the standard one, included by your header and brought into global namespace with using namespace std;
), there’s all kinds of pain to be had.
Worse, this problem gets promoted through every file that includes my header (which includes your header, which… you get the idea.)
Yes I know, in this example I am also to blame for not protecting my own classes in my own namespace, but that’s the one I came up with ad-hoc.
Namespaces are there to avoid clashes of identifiers. Your header not only introduces MyStuff
into the global namespace, but also every identifier from string
and fstream
. Chances are most of them are never actually needed by either of us, so why dragging them into global, polluting the environment?
Addition: From the view of a maintenance coder / debugger, foo::MyStuff
is ten times more convenient than MyStuff
, namespace’d somewhere else (probably not even the same source file), because you get the namespace information right there at the point in the code where you need it.