C++ Best Practice #1: Don't simply use: using namespace std; πŸ‘‹

Never try to import the whole std namespace into your program. Namespaces are developed to avoid naming conflicts. But, when we import the whole namespace there is a possibility that this could lead to name conflicts. You can do more harm than more good.

Description

using namespace std;

It is okay to import the whole std library in toy programs but in production-grade code, It is bad. using namespace std; makes every symbol declared in the namespace std accessible without the namespace qualifier. Now, let’s say that you upgrade to a newer version of C++ and more new std namespace symbols are injected into your program which you have no idea about. You may already have those symbols used in your program. Now the compiler will have a hard time figuring out whether the symbol declared belongs to your own implementation or from the namespace you imported without any idea. Some compilers throw errors. If you are unlucky, the compiler chose the wrong implementation and compile it which for sure leads to run time crashes.

For example, Consider the below code,

#include <iostreeam>
#include "foo.h" \\ Contains the implementation for same_as

using namespace std; \\Bad practice
class semiregular  { }; \\Implemented in foo.h

int main() {
  semiregular  b;
  ............
  cout << "Hello, Congrats.You are on your way to becoming an expert in programming...">>
}

The above code won’t trigger any compile-time error if compiled with C++17. It may throw an error when compiled with C++20 that the header file is not included. This is because semiregular is a feature implemented in C++20. So it’s always better to be on the safer side by not loading up your program with all the symbols a namespace offer. Instead use the :: annotation and use the full qualifier like std::cout.

#include <iostreeam>
#include "foo.h" \\ Contains the implementation for same_as

class semiregular  { }; \\Implemented in foo.h

int main() {
  semiregular  b;
  ............
  std::cout << "Hello, Congrats.You are on your way to becoming an expert in programming...">>
}

The above code didn’t load the whole of std so semiregular is not considered to be part of std and it considers the class implemented by us.

Conclusion

Never use “using namespace std;”. This also applies to all the namespaces. There is a possibility for naming conflict.