How 'using namespace' works in C++

1.7k Views Asked by At

I am trying to understand namespaces in C++. I read that there are two ways of accessing namespace variables and functions. First one is to write using :: and second one is by using using directive at the top and not writing it again and again. I realized that the first method is better as the second one may lead to conflicts.

But, I want to know how actually 2nd method is working. For Example, If I write using namespace std at the top, how does the compiler know for which functions it has to add std:: in the beginning and for which ones it has no to. If I have written a function in main, firstly it will check in my main file for the function and then it will check in the header files ( that I have declared at top of main file) for the function declaration. Now, according to my understanding the functions in std are declared inside namespaces. So, I will not find it if I search without using ::.

So, when will std:: will get add at the beginning of a function?

2

There are 2 best solutions below

3
On BEST ANSWER

(This is simplified, but it's the general gist of it.)

When you write std::bar, the compiler doesn't look for something named "std::bar", it looks for something named "bar" inside the "std" namespace.

using namespace std; makes the compiler look up names in both the current namespace and in std, so it doesn't need to add "std::" anywhere in order to look for "std::bar" - it will be found by looking for "bar" inside std as well as in the current namespace.

2
On

Here's a link to a description of how this works: http://en.cppreference.com/w/cpp/language/unqualified_lookup. A more general overview starts here(http://en.cppreference.com/w/cpp/language/lookup) and shows you all the cases when you have qualified names vs unqualified names.

Note that name resolution in C++ is actually quite complex. Argument Dependant Lookup (ADL) http://en.cppreference.com/w/cpp/language/adl can also apply when looking up where the function declaration is.

Also the compiler may need to do overload resolution as there can be multiple functions but with differing numbers of arguments and these overloads may exist in different namespaces.