Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a leading :: mean in "using namespace ::X" in C++

can somebody explain me the difference between the following namespace usages:

using namespace ::layer::module;

and

using namespace layer::module;

What causes the additional :: before layer?

like image 548
Dudero Avatar asked Jul 22 '11 12:07

Dudero


People also ask

What is the use of namespace in C?

Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

What is the meaning of using namespace?

The using namespace statement just means that in the scope it is present, make all the things under the std namespace available without having to prefix std:: before each of them.

How do you namespace helps in preventing global namespace in C++?

Namespace in C++ is the declarative part where the scope of identifiers like functions, the name of types, classes, variables, etc., are declared. The code generally has multiple libraries, and the namespace helps in avoiding the ambiguity that may occur when two identifiers have the same name.

What is the use of header file and namespace in C ++?

C language has numerous libraries that include predefined functions to make programming easier. In C language, header files contain the set of predefined standard library functions. You request to use a header file in your program by including it with the C preprocessing directive “#include”.


2 Answers

There would be a difference if it was used in a context such as:

namespace layer {
    namespace module {
        int x;
    }
}

namespace nest {
    namespace layer {
        namespace module {
            int x;
        }
    }
    using namespace /*::*/layer::module;
}

With the initial :: the first x would be visible after the using directive, without it the second x inside nest::layer::module would be made visible.

like image 187
CB Bailey Avatar answered Sep 24 '22 17:09

CB Bailey


A leading :: refers to the global namespace. Any qualified identifier starting with a :: will always refer to some identifier in the global namespace. The difference is when you have the same stuff in the global as well as in some local namespace:

namespace layer { namespace module {
    void f();
} }

namespace blah { 
  namespace layer { namespace module {
      void f();
  } }

  using namespace layer::module // note: no leading ::
                                // refers to local namespace layer
  void g() {
    f(); // calls blah::layer::module::f();
  }
}

namespace blubb {
  namespace layer { namespace module {
      void f();
  } }

  using namespace ::layer::module // note: leading ::
                                  // refers to global namespace layer
  void g() {
    f(); // calls ::layer::module::f();
  }
}
like image 24
sbi Avatar answered Sep 25 '22 17:09

sbi