Using the namespace in a function implementation

In C ++, is it possible to use a declaration using namespace std; in function implementation files?

+14
c ++ namespaces
source share
4 answers

By "function implementation files" do you mean .h or .cpp files? (Usually I call .cpp files "implementation" files, and .h files call "interface" files.)

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

If you mean .h files, you can, but you shouldn't. If you include it in an .h file, it will automatically apply to any .cpp file that contains an .h file that can contain many files. Typically, you do not want to tell other modules which namespaces to import. It is best to put it in every .cpp file, rather than in a regular .h file.

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

+14
source share

You might also want to know what you can put using namespace std; functions inside the body as shown below. This will limit 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 many elements of the namespace in the body of a function that is written in the header file (which you do not have to by yourself, but sometimes this is normal or even almost necessary (for example, templates)).

+94
source share

I assume you mean something like this:

 // Foo.h void SayHello(); 

...

 // Foo.cpp #include "Foo.h" using namespace std; void SayHello() { cout << "Hello, world!" << endl; } 

If so, then yes. However, he believed that bad practice uses using namespace std; in larger projects.

+7
source share

If by "function implementation files" you mean .C / .cpp files, etc., you can, however, try to avoid. Instead, enter only what you need, for example, if you need <iostream> for std::cout , std::endl , etc. Just enter these two using std::cout; and using std::endl; , now you can just write cout and endl .

+4
source share

All Articles