Search code examples
c++namespacesname-lookupusing-directivesusing-declaration

Extremely basic question about namespaces in c++


using namespace X;
    cout << var;
    using Y::var;
    cout << var;

So say I have a namespace X and a namespace Y that both contain a variable of type int called var. When I say using namespace X; what I imagine happening is if I use some variable that isn't in the global namescope what basically happens is it goes okay I'm gonna look for var in namespace X but now that I also use Y::var what does this exactly mean? Does that just say var is the same as Y::var? But then in that case what's happening with using namespace X does it not even look for var in there because I said I'm using Y::var?


Solution

  • After the using directive

    using namespace X;
    

    the compiler uses the unqualified name lookup to find the name var used in the following statement

    cout << var;
    

    And due to the using directive it will find the variable var in the namespace X.

    This using declaration

    using Y::var;
    

    introduces the variable var from the namespace Y in the current scope and the next statement

    cout << var;
    

    will use the variable var from the namespace Y.

    Here is a demonstration program.

    #include <iostream>
    
    namespace X
    {
        int var = 1;
    }
    
    namespace Y
    {
        int var = 2;
    }
    
    int main() 
    {
        using namespace X;
    
        std::cout  << "var = " << var << '\n';
    
        using Y::var;
    
        std::cout  << "var = " << var << '\n';
    }
    

    The program output is

    var = 1
    var = 2
    

    That is the using declaration that introduces the variable var in the block scope of the function main hides the declaration of the variable var declared in the namespace X.

    In fact the below simplified demonstration program in essence behaves similarly as the above program relative to the name lookup.

    #include <iostream>
    
    int var = 1;
    
    int main() 
    {
        std::cout  << "var = " << var << '\n';
    
        int var = 2;
    
        std::cout  << "var = " << var << '\n';
    }