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

links77 picture links77 · Nov 21, 2011 · Viewed 94k times · Source

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?

Answer

Roee Gavirel picture Roee Gavirel · Nov 21, 2011

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.