Extending namespace and Unnamed namespace


Here we will see how we can extend some namespace, and how the unnamed or anonymous name space can be used.

Sometimes we can define one namespace. Then we can write the namespace again with the same definition. If the first one has some member, and second one has some other members, then the namespace is extended. We can use all of the members from that namespace.

Example

#include <iostream>
using namespace std;
namespace my_namespace {
   int my_var = 10;
}
namespace my_namespace { //extending namespace
   int my_new_var = 40;
}
main() {
   cout << "The value of my_var: " << my_namespace::my_var << endl;
   cout << "The value of my_new_var: " << my_namespace::my_new_var << endl;
}

Output

The value of my_var: 10
The value of my_new_var: 40

The unnamed namespace will not have any names; These have different properties.

  • They are directly usable in same program.
  • These are used to declare unique identifiers.
  • In this type of namespace name of the namespace is uniquely generated by compiler itself.
  • This can be accessed from that file, where this is created.
  • Unnamed namespaces are the replacement of the static declaration of variables.

Example

#include <iostream>
using namespace std;
namespace {
   int my_var = 10;
}
main() {
   cout << "The value of my_var: " << my_var << endl;
}

Output

The value of my_var: 10

Updated on: 30-Jul-2019

175 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements