c++namespacestoken-name-resolution

How 'using namespace' works in C++


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?


Solution

  • (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.