Quote:
Originally Posted by sickufully
I have no idea why this is a bad idea (please enlighten me on why, curious to know) but that's just what the teacher supplied us with. I dunno if he did it for us c++ newbies or if he actually writes his code like that.
|
There's multiple reasons why
using namespace whatever; is generally a bad idea. Consider this situation for a moment:
Code:
namespace Foo
{
void Func()
{
// Does something!
}
}
namespace Bar
{
void Func()
{
// Does something completely different!
}
}
using namespace Foo;
using namespace Bar;
Func(); // Error! Can't figure out which one to call
If you have functions with the same name in multiple namespaces it can cause great confusion and even compiler errors when you try to call those functions without the namepspace prefix. Now with the same example, if the
using namespace statements are not used it would look like this:
Code:
// Now you can clearly see which function is being called. Nice!
Foo::Func();
Bar::Func();
It ultimately comes down to preference, but I've found that most programmers are against
using namespace for the above reasons. The only times I've really seen it used are when there are a lot of nested namespaces like the following:
Code:
namespace Engine
{
namespace Tools
{
namespace UI
{
void Foo();
}
}
}
// This is quite a pain to have to type EVERY single time you need this function...
Engine::Tools::UI::Foo();
Hopefully that's not too confusing XD Not sure how crazy I should get with these examples. I tried to keep it simple. Hope it helps!
EDIT: Oh! As a sidenote, if you find yourself stuck on a problem for a long time
http://www.stackoverflow.com is a great reference for asking or searching for common questions. Also, if you're ever unsure of what a standard function does,
http://en.cppreference.com/w/ has you covered