In computing, a namespace is used to avoid name collisions when using multiple libraries, a namespace is a declarative prefix for functions, classes, types, etc. In this article, I will explain to you the concept of a namespace is the C++ programming language.
Introduction to Namespace in C++
The C++ namespace is a collection of C++ entities (functions, classes, variables), whose names are prefixed by the name of the namespace.
Also, Read – Pattern Programming using the C++ Programming Language.
When writing code in a namespace, named entities belonging to that namespace do not need to be preceded by the name of the namespace, but entities outside of it must use the fully qualified name. The full name has the format <namespace> :: <entity>. For example:
namespace Example { const int test = 5; const int test2 = test + 12; //Works within `Example` namespace } const int test3 = test + 3; //Fails; `test` not found outside of namespace. const int test3 = Example::test + 3; //Works; fully qualified name used
Namespaces are useful for grouping related definitions. Take the analogy of a shopping mall. Usually, a mall is divided into several stores, each store selling items of a specific category.
One store can sell electronics, while another can sell shoes. These logical separations in store types help shoppers find the items they’re looking for.
Namespaces help C++ programmers, like buyers, find the functions, classes, and variables they are looking for by organizing them logically. For example:
namespace Electronics { int TotalStock; class Headphones { // Description of a Headphone (color, brand, model number, etc.) }; class Television { // Description of a Television (color, brand, model number, etc.) }; } namespace Shoes { int TotalStock; class Sandal { // Description of a Sandal (color, brand, model number, etc.) }; class Slipper { // Description of a Slipper (color, brand, model number, etc.) }; }
There is only one predefined namespace, which is the global namespace which has no name but can be referred to as ::. For example:
void bar() { // defined in global namespace } namespace foo { void bar() { // defined in namespace foo } void barbar() { bar(); // calls foo::bar() ::bar(); // calls bar() defined in global namespace } }
Hope you liked this article on the concept of namespaces in the C++ programming language. Please feel free to ask your valuable questions in the comments section below.