Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a C++ namespace in header and source (cpp)

Tags:

c++

namespaces

Is there any difference between wrapping both header and cpp file contents in a namespace or wrapping just the header contents and then doing using namespace in the cpp file?

By difference I mean any sort performance penalty or slightly different semantics that can cause problems or anything I need to be aware of.

Example:

// header namespace X {   class Foo   {   public:     void TheFunc();   }; }  // cpp namespace X {   void Foo::TheFunc()   {     return;   } } 

VS

// header namespace X {   class Foo   {   public:     void TheFunc();   }; }  // cpp using namespace X; {   void Foo::TheFunc()   {     return;   } }  

If there is no difference what is the preferred form and why?

like image 657
links77 Avatar asked Nov 21 '11 11:11

links77


People also ask

Can you use a namespace in a header file?

You should definitely NOT use using namespace in headers for precisely the reason you say, that it can unexpectedly change the meaning of code in any other files that include that header. There's no way to undo a using namespace which is another reason it's so dangerous.

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 we create our own namespace in C++?

C++ allows us to define our own namespaces via the namespace keyword. Namespaces that you create for your own declarations are called user-defined namespaces. Namespaces provided by C++ (such as the global namespace ) or by libraries (such as namespace std ) are not considered user-defined namespaces.

What is difference between header file and namespace in C++?

A header file is a file that is intended to be included by source files. They typically contain declarations of certain classes and functions. A namespace enables code to categorize identifiers. That is, classes, functions, etc.


1 Answers

The difference in "namespace X" to "using namespace X" is in the first one any new declarations will be under the name space while in the second one it won't.

In your example there are no new declaration - so no difference hence no preferred way.

like image 50
Roee Gavirel Avatar answered Sep 21 '22 21:09

Roee Gavirel