What does 'using namespace std' mean in C++?


Consider a situation, when we have two persons with the same name, Piyush, 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 a different area or their mother’s or father’s name, etc.

The 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.

A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. Using namespace, you can define the context in which names are defined. In essence, a namespace defines a scope.

C++ has a standard library that contains common functionality you use in building your applications like containers, algorithms, etc. If names used by these were out in the open, for example, if they defined a queue class globally, you'd never be able to use the same name again without conflicts. So they created a namespace, std to contain this change.

The using namespace statement just means that in the scope it is present, make all the things under the std namespace available without having to prefix std:: before each of them.

While this practice is okay for short example code or trivial programs, pulling in the entire std namespace into the global namespace is not a good habit as it defeats the purpose of namespaces and can lead to name collisions. (Even if there are initially no name collisions, they can crop up during maintenance as more code, libraries, etc. are added to the project.) This situation is commonly referred to as namespace pollution.

Updated on: 30-Jul-2019

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements