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

nickolay picture nickolay · May 30, 2012 · Viewed 59k times · Source

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?

Answer

Dan F picture Dan F · May 30, 2012

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