Introduction

Namespace is a container for identifiers. It puts the names of its members in a distinct space so that they don’t conflict with the names in other namespaces. Namespaces allow to group entities like classes, objects and functions under a name.

Syntax

Namespace definition doesn’t terminates with a semicolon like in class definition. Unnamed namespace is unique for each translation unit. They act exactly like named namespaces. A namespace definition can be continued and extended over multiple files, they are not redefined or overriden.

// Named Namespace
namespace ns_name { 
  declarations 
}	

// Unnamed Namespace
namespace { 
  declarations 
}

This will create a new namespace called ns_name.

Using a Namespace

A identifier declared in a namespace can be explicitly specified using the namespace’s name and the scope resolution :: operator with the identifier. using keyword import an entire namespace into program with a global scope. using keyword is also used for accessing identifier from a namespace into the current declarative region.

using namespace std;

namespace constant
{
  double pie = 3.1416;
}

int main() {
 
  using constant::pie;
 
  cout << pie;
  
  return 0;
}

 

Example

In the below example class Shape is defined in a namespace Bottom. Bottom namespace is defined under the namespace Top.

using namespace std;

namespace Top {

  // Bottom is a member of Top
  namespace Bottom { 

    // Shape is a member of Bottom and is fully defined within it
    class Shape { 
      int h;
      int w;

    public:
      Shape(int a, int b) {
        h = a;
        w = b;
      }

      int area(); 
    }; 
  }

  // cout is a member of Top
  void cout(int);

  // Definition of Bottom::Shape::area
  int Bottom::Shape::area()  {
    return h * w;
  }
}

// Definition of Top member
void Top::cout(int val) {
  std::cout << val;
}

int main()
{
  Top::Bottom::Shape s(2, 3);
  Top::cout(s.area());

  return 0;
}

Reference

Namespaces