user1008636
user1008636

Reputation: 3181

Accessing an 'parent' namespace in c++?

I've run into a piece of code in a cpp file that looks like this:

using namespace `A::B::C`
namespace A::B::C{  
  void function(){
    if (X::myVariable){
      //...
    }
}

where myVariable was defined in a different cpp file:

namespace A::X{
   bool myVariable = 2;
}

What I don't understand is why in the void function() under namespace A::B::C it was able to access X::myVariable.

Upvotes: 1

Views: 350

Answers (1)

Ryan Haining
Ryan Haining

Reputation: 36802

You are allowed to reopen a namespace, the namespace A is the same A in both places. When the compiler looks up the name X it looks for it in A::B::C, A::B, A, and the global namespace. It finds X in A.

The inner namespace has implicit access to the outer namespace. This is also allowed:

namespace A {
  constexpr int top = 1;
  namespace B {
    constexpr int middle = top + 1;
    namespace C {
      constexpr int bottom = middle + top;
    }
  }
}

live link

Upvotes: 2

Related Questions