6
namespace MyNamespace
{
    static void foo1()
    {

    }
}

using namespace MyNamespace;

class MyClass
{
    void foo2()
    {
        ::foo1();
    }    
};

The scope resolution operation :: means using method in the global namespace. Here we can use ::foo1(). This means method foo1() is in the global namespace, am I right?

My question is, does using namespace ANAMESPACE_NAME mean we import all elements form the namespace ANAMESPACE_NAME into the global namespace?

4 Answers 4

5

No. "using namespace ANAMESPACE_NAME" mean we import all elements into current scope.

You can write something like this:

namespace A {
    int i = 10, j = 20;
}

int f()
{
    using namespace A;  // injects names from A into the global scope.
    return i * j;       // uses i and j from namespace A.
}

int k = i * j; // Error: undefined variant i and j.
Sign up to request clarification or add additional context in comments.

1 Comment

+1: Using-directives don't always have to be in global scope.
3

Section 3.4.3.4 of the C++2003 standard has an answer:

A name prefixed by the unary scope operator :: (5.1) is looked up in global scope, in the translation unit where it is used. The name shall be declared in global namespace scope or shall be a name whose declaration is visible in global scope because of a using-directive (3.4.3.2).

This paragraph is almost identical in the C++11 FDIS, so this probably also holds in C++11.

Comments

3

Here we can use ::foo1(). This means method foo1() is in the global namespace, am I right?

Yes thats correct. It means call the method named foo1() defined in global namespace. This is called as Qualified Namespace Lookup.

do "using namespace ANAMESPACE_NAME" mean we import all elements in the ANAMESPACE_NAME namespace into global namespace?

Yes, it imports all elements from the ANAMESPACE_NAME namespace in to current namespace.
It is called as an using directive.
If you want to import just specific element in current type use, using declaration.

format is:

using ANAMESPACE_NAME::element_name;

Comments

0

YEs -

http://www.cplusplus.com/doc/tutorial/namespaces/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.