C++ Namespaces

Share on facebook
Share on twitter
Share on linkedin
Share on twitter
Share on tumblr

In this C++ tutorial, let us see Namespaces in C++, its declaration and sample C++ program to understand this concept better.

Introduction of C++ Namespaces

Namespaces allow us to group named entities that otherwise would have global scope into narrower scopes, giving them namespace scope. This allows organizing the elements of programs into different logical scopes referred to by names.


namespace identifier

Where identifier is any valid identifier and named_entities is the set of variables, types and functions that are included within the namespace. 

For example

namespace myNamespace
  int a, b;

In this case, the variables a and b are normal variables declared within a namespace called myNamespace.

These variables can be accessed from within their namespace normally, with their identifier (either a or b), but if accessed from outside the myNamespace namespace they have to be properly qualified with the scope operator(::) 

For example, to access the previous variables from outside myNamespace they should be qualified like:


Namespace declaration types

Namespaces can be split into two segments of code can be declared in the same namespace as follows,

namespace foo { int a; }
namespace bar { int b; }
namespace foo { int c; }

This declares three variables: a and c are in namespace foo, while b is in namespace bar. Namespaces can even extend across different translation units (i.e., across different files of source code).

Program for C++ Namespaces

Namespaces are particularly useful to avoid name collisions. For example:

// namespaces
#include <iostream>
using namespace std;
namespace foo
  int value() { return 5; }
namespace bar
  const double pi = 3.1416;
  double value() { return 2*pi; }
int main () {
  cout << foo::value() << '\n';
  cout << bar::value() << '\n';
  cout << bar::pi << '\n';
  return 0;




Leave a Comment

Your email address will not be published. Required fields are marked *