Namespaces

Namespaces are ways of collecting symbols (function names, class names, etc...) into logical groups. They are used to help:

  1. avoid naming conflicts that can occur when large numbers of people work on the same project.
  2. organize the pieces of code that logically go together as a unit

These affect how we use everything from the standard C++ libraries.

Whenever we want to use anything from a namespace, we need to declare it as coming from that particular namespace. For example, everything in the standard C++ libraries belongs to the namespace "std". We used to be able to code:

#include <iomanip>

int main()
  {
  int i;
  double d;
  
  cout << "Enter an integer: ";
  cin >> i;
  
  cout << "Enter a double: ";
  cin >> d;
  
  return 0;
  }

This will not compile. cin and cout belong to the standard namespace and must be used as such. To specify that an object belongs to a namespace, use the following format:

namespace_name::object_name

So the program now becomes:

#include <iomanip>

int main()
  {
  int i;
  double d;
  
  std::cout << "Enter an integer: ";
  std::cin >> i;
  
  std::cout << "Enter a double: ";
  std::cin >> d;
  
  return 0;
  }

This can get pretty ugly very quickly. Fortunately, there is a solution, the keyword "using".

The are two formats for "using":

  1. using declaration
  2. using directive

using declaration

With this type of using, the symbols that are going to be used from a given namespace will be declared. This declaration is placed at the beginning of the program, along with the #define's and function prototypes. The format for this is:

using namespace_name::object_name;

Now our program becomes:

#include <iomanip>

using std::cout;
using std::cin;

int main()
  {
  int i;
  double d;
  
  cout << "Enter an integer: ";
  cin >> i;
  
  cout << "Enter a double: ";
  cin >> d;
  
  return 0;
  }

If a lot of different things are being used from a namespace, there would be a lot of using declarations at the beginning. This is OK.

using directive

With a using directive, the entire namespace is declared, rather than declaring each symbol. The format for this is:

using namespace namespace_name;

This last usage is very common, but it is considered bad programming style.