Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Namespaces -- How to use in header and source files correctly?

Consider a pair of two source files: an interface declaration file (*.h or *.hpp) and its implementation file (*.cpp).

Let the *.h file be like the following:

namespace MyNamespace {   class MyClass {   public:     int foo();   }; } 

I have seen two different practices for using namespaces in source files:

*.cpp showing practice #1:

#include "MyClass.h" using namespace MyNamespace;  int MyClass::foo() { ... } 

*.cpp showing practice #2:

#include "MyClass.h" namespace MyNamespace {    int MyClass::foo() { ... }  } 

My question: Are there any differences between these two practices and is one considered better than the other?

like image 201
nickolay Avatar asked May 30 '12 12:05

nickolay


People also ask

Should namespaces be in header files?

Code in header files should always use the fully qualified namespace name. The following example shows a namespace declaration and three ways that code outside the namespace can accesses their members.

Can you use namespace std in a header file?

Since you can't put a namespace using statement at the top level of the header file, you must use a fully qualified name for Standard Library classes or objects in the header file. Thus, expect to see and write lots of std::string, std::cout, std::ostream, etc. in header files.

Where should I put using namespace?

You would be best to just use it in the functions that you need it, or even not use it at all and just prefix standard library functions/classes with std:: .

Can you include header files in header files C?

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”. All the header file have a '. h' an extension.


1 Answers

From a code readability standpoint, it is probably better in my opinion to use the #2 method for this reason:

You can be using multiple namespaces at a time, and any object or function written below that line can belong to any of those namespaces (barring naming conflicts). Wrapping the whole file in a namespace block is more explicit, and allows you to declare new functions and variables that belong to that namespace within the .cpp file as well

like image 102
Dan F Avatar answered Oct 12 '22 22:10

Dan F