What's the scope of the "using" declaration in C++?

Solution 1:

There's nothing special about header files that would keep the using declaration out. It's a simple text substitution before the compilation even starts.

You can limit a using declaration to a scope:

void myFunction()
{
   using namespace std; // only applies to the function's scope
   vector<int> myVector;
}

Solution 2:

When you #include a header file in C++, it places the whole contents of the header file into the spot that you included it in the source file. So including a file that has a using declaration has the exact same effect of placing the using declaration at the top of each file that includes that header file.

Solution 3:

The scope of the using statement depends on where it is located in the code:

  • Placed at the top of a file, it has scope throughout that file.
  • If this is a header file, it will have scope in all files that include that header. In general, this is "not a good idea" as it can have unexpected side effects
  • Otherwise the using statement has scope within the block that contains it from the point it occurs to the end of the block. If it is placed within a method, it will have scope within that method. If it is placed within a class definition it will have scope within that class.