Some people always like to use it and ask me why I don’t.
First of all, using the
using namespace std is a good practice, but it shouldn’t be used always and for all.
I avoid using it for 2 basic reasons:
1st. I like to know which library that declaration/function is part of.
Sometimes you are using a library that has the same function name. For example, suppose you have this code with this namespace:
In this example we see a:
using namespace std;, look what an unfortunate mess!!! 😞
When I try to compile I’ll have a nice error:
That’s because my string type is different from the
string type of the std scope resolution I used:
using namespace std;. Separate by declaration, I think better than using in general, eg
using std::cout; , but even so, it gets a little messy!
If we remove the
using namespace std; and declare each one in its square, the code compiles without problems:
But if you have
terror::stringyou notice that the compiler does a better job of helping you.
Ahh!!! But who will create names for functions, classes, structs, … with names that already exist in the STL? That’s what else there is.
In the Unreal Engine libraries, there is even
vector, and it is not the std vector.
Without mentioning the
abs example, I’ve seen a lot of people using function names that already exist in the STL and this can give a lot of headaches if the guy always uses namespace without scope resolution.
2nd. I don’t know where that came from
For example, this day I was creating code with OpenCV and there is a type/class that is
VideoCapture and in their documentation they use
using namespace cv;, it took a while, but I found out that VideoCapture is actually
cv::VideoCapture and this has already happened to me several times mostly with
That’s why I don’t like to use it and I don’t recommend it, as do many programmers I know, but it’s worth mentioning that this is a matter of taste, ok?!
That’s all for today, small daily doses that will always keep us in tune with C++!