Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Nishtha Thakur

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

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.