Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: using namespace

📅 2010-Jul-06 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 Archive

A lot of C++ libraries make good use of namespaces, including the C++ standard library itself, which uses the std namespace. The best way to use a name that is defined within a different namespace is to qualify it everywhere with its namespace:

std::cout << "Hello!";

Qualifying every name from a namespace at every instance of its use can become quickly tiring. It may seem convenient to pull in all the names from a namespace into a header or source file:

using namespace std;

C++ experts however frown upon this practice. It can foster bugs in code when two or more names in the same space have different definitions. They prefer the practice of pulling in specific names that are frequently used from the namespace:

using std::cout;
cout << "Hello!";

Personally, I find the above practice of specific names quite ugly. I prefer the fully qualified name, or in the worst case I would use using namespace, but with one precaution: use it only in the source files and not in the header files. This is because once using namespace is introduced into a header file, it can spread virally everywhere from there.