Namespaces in C++

Namespace is nothing but a container for identifiers. It places the names of its members in a separate space so that they don’t conflict with the names in further namespaces or else global namespace.

Creating a Namespace

Producing a namespace is alike to creation of a class.

namespaceMySpace
{
 // Declarations
}

int main() {}

This will create a namespace namedMySpace, inside which we can place our member declarations.

Guidelines to create Namespace

  1. The namespace definition must be prepared at global scope, otherwise nested inside added namespace.
  2. Namespace definition doesn’t ends with a semicolon similar in class definition.
  3. You can use an identified name for your namespace name, for comfort of use.

Example :

  1. You cannot form instance of namespace.
  2. There can be unnamednamespaces also. Unnamed namespace is exclusive for every translation unit. They act preciselysimilar named namespaces.

Example :

 

Using a Namespace

There are three methods to use a namespace in program,

With Scope Resolution

Any name stated in a namespace can be explicitly identified using the namespace’s name also the scope resolution:: operator with the identifier.

 

The using directive

The using keyword lets you to import awhole namespace into your program with a global scope. It can be used to import a namespace into alternative namespace or else any program.

Here,We imported the namespace X into namespace Y, therefore class Check is accessible in namespace Y.

Therefore, the using directive makes it a lot at ease to use namespace, anywhere you want.

The using declaration

if we use using directive, we import altogether the names in the namespace .they are accessible throughout the program, i.e. they have global scope.

On the other hand with using declaration, we import one particular name at a time which is available simply inside the current scope.

Here, we never say the argument list of a function while bring in it, therefore if a namespace has overloaded function, it will lead to improbability.

Leave A Comment

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