using namespace in function implementation

Maybe you would like to know too that you can put using namespace std; within a function body as well, like below. This will restrict the scope of the using namespace statement.

void f() {
  using namespace std;
  cout << "Foo" << endl;
  //..
};

void g() {
  cout << "Bar" << endl; //ERROR: cout and endl are not declared in this scope.
};

This can be useful if you want to use a lot of elements of a namespace in the body of a function that is written in a header file (which you shouldn't per se, but sometimes it is OK or even almost necessary (e.g. templates)).


I'm assuming you mean something like this:

// Foo.h

void SayHello();

...

// Foo.cpp

#include "Foo.h"

using namespace std;

void SayHello()
{
    cout << "Hello, world!" << endl;
}

If that is the case, then yes. However, it's considered bad practice to use using namespace std; in larger projects.


By "function implementation files" do you mean the .h files or the .cpp files? (I would normally call .cpp files "implementation" files, while .h files are "interface" files.)

If you mean, .cpp files, then of course. That is where you normally see using namespace std. It means that all the code in this .cpp file has access to std without qualification.

If you mean .h files, then you can, but you shouldn't. If you include it in a .h file, it will automatically apply to any .cpp file which includes the .h file, which could be a lot of files. You generally don't want to be telling other modules which namespaces to import. It is best to put it in every .cpp file rather than in a common .h file.

Edit: User @lachy suggested an edit which I won't include verbatim, but they suggested I point out that using namespace std is usually considered bad practice, due to namespace pollution. They gave a link to a question on this topic: Why is "using namespace std;" considered bad practice?

Tags:

C++

Namespaces