Namespaces in C++
Namespaces in C++
NAMESPACES IN C++
Consider a situation, when we have two persons with the same name,
Zara, in the same class.
Whenever we need to differentiate them definitely we would have to
use some additional information along with their name, like either
the area, if they live in different area or their mother’s or father’s
name, etc.
Same situation can arise in your C++ applications.
For example, you might be writing some code that has a function
called xyz() and there is another library available which is also having
same function xyz().
Now the compiler has no way of knowing which version of xyz()
function you are referring to within your code.
NAMESPACES IN C++
If we compile and run above code, this would produce the following
result −
Inside first_space
Inside second_space
THE USING DIRECTIVE
You can also avoid prepending of namespaces with the using namespace directive.
This directive tells the compiler that the subsequent code is making use of names in
the specified namespace. The namespace is thus implied for the following code −
// second name space
#include <iostream>
namespace second_space {
using namespace std;
void func() {
cout << "Inside second_space" << endl;}
// first name space
}
namespace first_space
using namespace first_space;
{
int main ()
void func() {
{
cout << "Inside first_space" << endl;
// This calls function from first name space.
}
func();
}
return 0;
}
THE USING DIRECTIVE
The ‘using’ directive can also be used to refer to a particular item within a namespace. For
example, if the only part of the std namespace that you intend to use is cout, you can refer to it
as follows −
using std::cout;
Subsequent code can refer to cout without prepending the namespace, but other items in
the std namespace will still need to be explicit as follows −
#include <iostream>
using std::cout;
int main ()
{
cout << "std::endl is used with std!" << std::endl;
return 0;
}