namespace namespace_name
{
// code declarations i.e. variable (int a;)
method (void add();)
classes ( class student{};)
}
namespace_name::code
namespace namespace_name1
{
// code declarations
namespace namespace_name2
{
// code declarations
}
}
Example
#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;
}
Let us see how namespace scope the entities including variable and functions
#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;
}
}
int main ()
{
// Calls function from first name space.
first_space :: func();
// Calls function from second name space.
second_space :: func();
return 0;
}