4

From my understanding, appending :: to the front of a namespace refers to the global namespace, regardless of any using statements or parent namespaces. If that is the case, and I haven't mis-understood anything, then why does such code compile (at least in Visual Studio):

namespace Foo { namespace Bar { class X; } } using namespace Foo; int main(void) { ::Bar::X x; } 
1
  • Because a using directive imports everything. Commented Aug 9, 2013 at 20:50

1 Answer 1

6

using namespace Foo; brings all the contents of namespace Foo into the context of the current namespace.

Since namespace Bar is among the contents of namespace Foo and the current namespace on the line with the using statement is the global namespace, namespace Bar is brought into the context of the global namespace.

Sign up to request clarification or add additional context in comments.

8 Comments

Ahh, okay thanks. I assumed that was what was happening, but I just wanted to make sure. I was really hoping :: overrides using statements, but I guess we don't always get what we want :/
@Duncan :: at the start of a statement is going to refer to scope resolution on the global namespace regardless of what using statements you've introduced. What do you mean by wanting it to "[override] using statements"?
@Duncan just to be clear namespace K { using namespace Foo; } puts the content of the namespace Foo under K::, that's all is happening here, except for the fact that the global namespace :: is implied.
Take for example if I had put using namespace Foo::Bar instead. Then, if someone referred to ::X in their code, then there is no easy way of knowing whether that was a reference to Foo::Bar::X or if there is a class X defined elsewhere outside of a namespace. I'm really just nit-picking at this point.
@Duncan But that's a problem you'll always encounter. Keep in mind that you can always use the fully qualified path to the type: ::Foo::Bar::X - even if you have a using namespace Foo::Bar; statement.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.