Open In App

Can namespaces be nested in C++?

Improve
Improve
Like Article
Like
Save
Share
Report

In C++, namespaces can be nested, and resolution of namespace variables is hierarchical. For example, in the following code, namespace inner is created inside namespace outer, which is inside the global namespace. In the line “int z = x”, x refers to outer::x. If x would not have been in outer then this x would have referred to x in global namespace. 

Namespaces can be nested where you can define one namespace inside another name space as follows:

namespace namespace_name1 {
  // code declarations
  namespace namespace_name2 {
     // code declarations
  }
}

You can access members of nested namespace by using resolution operators as follows:

// to access members of namespace_name2
using namespace namespace_name1::namespace_name2;
// to access members of namespace_name1
using namespace namespace_name1;

In the above statements if you are using namespace_name1, then it will make elements of namespace_name2 available in the scope as follows:

C++




#include <iostream>
using namespace std;
 
// first name space
namespace first_space{
   void func(){
      cout << "Inside first_space" << endl;
   }
   // second name space
   namespace second_space{
      void func(){
         cout << "Inside second_space" << endl;
      }
   }
}
using namespace first_space::second_space;
int main ()
{
  
   // This calls function from second name space.
   func();
    
   return 0;
}
 
// If we compile and run above code, this would produce the following result:
// Inside second_space


Output

Inside second_space

 

CPP




#include<iostream>
 
int x = 20;
namespace outer
{
  int x = 10;        
  namespace inner
  {
    int z = x; // this x refers to outer::x
  }
}
 
int main()
{
  std::cout<<outer::inner::z; //prints 10
  getchar();
  return 0;
}


Output

10

Output of the above program is 10. On a side node, unlike C++ namespaces, Java packages are not hierarchical.



Last Updated : 10 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads