Skip to main content
GameDev.net gamedev.net
🔒 Locked

[c++] 'using namespace std;' Good practice?

Started by gimp Jul 2, 2002 at 7:32 PM 3 replies 1.3k views
Original Post
gimp
gimp
I''m after the zen of using namespaces. Furing my formative time in learning c++, someone online disuaded me from ''using namespace std'', and, prefer using the fully qualified namepsace std::string boost::tokenizer, etc. Can anyone think of the pro''s \ con''s of doing this vs just prepending each file with : using namespace std; using namespace boost; using namespace MyLib; etc Thoughts? Chris Brodie http:\\fourth.flipcode.com
Chris Brodie
Oluseyi
Oluseyi
If you declare using namespace XYZ; at the top of a file, then all symbols within that namespace are "imported". This isn''t a problem in a closed compilation unit (source file), but if the file will be introduced to other compilation units (header file), then it''s just plain wrong. In summary, use fully qualified object names in headers, and feel free to introduce the entire namespace into source files, but beware the potential for collisions (which will be resolved by full qualification). It makes no sense to introduce two namespaces and then have them generate collisions.
DerekSaw
DerekSaw
I suggest to use "using namespace std;" ONLY under .CPP.
For .H, it is better to have this:

class MyClass
{
...
public:
std::string & GetName() const { return _name; }
...
private:
std::string _name;
};

"after many years of singularity, i'm still searching n the event horizon" o
Cedric
Cedric
Oluseyi''s right, you should not write ''using namespace std'' in a header file (unless you''re the sole manager of your project and you don''t want anyone else to ever use your headers). However, here''s something I just thought of and I don''t know if it''s right or wrong, I''m just throwing the idea:

namespace A{
using namespace std;

//Code can use std
};

//Code has to specify std::

This code could be put in a header file without ''polluting'' the translation unit with std::. However, it has the consequence that if someone writes ''using namespace A'', it also includes all of std. If there''s a warning about it, I would say that it''s OK.

Cédric
gimp
gimp
Yep that makes sence. I was new and probably was using namespaces right there in the header and when warned off decided not to declare namespace use at call doing all calls the long way.

Thanks all.

Chris Brodie
http:\\fourth.flipcode.com
Chris Brodie

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.