Namespaces

Namespace :

Namespace are used to prevent name collisions that can occur especially when your code base includes multiple libraries. Suppose there two libraries each having function of same name, say, func(). So, when we use func(), compiler doesn’t know which func() of the either libraries are you referring to. Namespaces provide the solution to this problem.

Namespace is a declarative region that define the scope of the identifiers(variables, function names, class names etc. ) used inside it.  It puts the names of its members in a distinct space so that they don’t conflict with the names in other namespaces.

Defining the namespace :

  • namespace keyword is used to define a namespace.
  • Namespaces are generally declared in different header files

Syntax for defining namespace is :
namespace namespace_name
{
….
…….
….
}

Alias name for namespace :

 

Namespace alias serves as an abbreviation for the actual name.
e.g.

Using the identifiers from namespace :

Using scope resolution operator : namespace_name::identifier
To use a single identifier at a time from a namespace. You have to use above format everytime you have to use that identifier.
e.g

Output :
i=20
Hello function

Using using directive  :

  • Syntax : using namespace_name::identifier;
  • To use a single identifier from a namespace. You have to use above format one time for a identifier to get it into scope.

e.g.

Output :

  • Syntax : using namespace namespace_name;
  • It bring everything in the namespace into scope.

e.g. 

Output :

  • A namespace can be declared in multiple blocks in a single file, and in multiple files.
  • We can also define the members outside the namespace.
  • The compiler joins the parts together during pre-processing and the resulting namespace contains all the members declared in all the parts.An example of this is the std namespace which is declared in each of the header files in the standard library.
e.g. 

Output :

i=20
Hello function

Nested Namespaces : 
Namespaces can be nested one into another.
e,g.

Output :

i=20
Function Child

Leave a Reply

Your email address will not be published. Required fields are marked *