Namespaces

Introduction

  • Namespaces allow to group entities like classes, objects and functions under a name.
  • This way the global scope can be divided in "sub-scopes", each one with its own name.
  • By default, all variables and functions are defined in the global namespace.

The scope resolution operator (::)

This operator allows you to prefix an identifier name with the namespace you wish to use.

The using keyword

The keyword using is used to introduce a name from a namespace into the current declarative region.

Examples

Example 1

namespace myNamespace
{
  int a, b;
}

In order to access these variables from outside the myNamespace namespace we have to use the scope operator ::. For example, to access the previous variables from outside myNamespace we can write:

myNamespace::a
myNamespace::b

Example 2

// using
#include <iostream>
using namespace std;
 
namespace first
{
  int x = 5;
  int y = 10;
}
 
namespace second
{
  double x = 3.1416;
  double y = 2.7183;
}
 
int main () {
  using first::x;
  using second::y;
  cout << x << endl;
  cout << y << endl;
  cout << first::y << endl;
  cout << second::x << endl;
  return 0;
}

Example 3: In the following code which functions are called and why?

namespace A
{
  struct X;
  struct Y;
  void f(int);
  void g(X);
}
 
namespace B
{
  void f(int i)
  {
    f(i); //1. which f()?
  }
  void g(A::X x)
  {
    g(x); //2. which g()?
  }
  void h(A::Y y)
  {
    h(y);  //3. which h();
  }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.