Saturday 2 October 2010

NAME SPACES



NAME SPACES

Name spaces prevent pollution of global namespace that leads to name clashes.  The term ‘global name space’ refers to the entire source code. By default, the name of each class is visible in the entire source code, that is, in the global name space. This can lead to problems.

The following examples make these things clear.

Suppose a class with the same name is defined in two header files.

//Beginning of A1.h
class A
{
   // some code
}

//Beginning of A2.h
class A
{
   // some code
}

Now let us include these two header files in a program and see what happens if we declare an object of the class

#include “A1.h”
#include “A2.h”
void main()
{
A aObj;   // Ambiguity Error due to multiple definitions of A.

}

The above problem can be solved with the help of namespaces.

//Beginning of A1.h
namespace A1      //beginning of a namespace A1
{
class A
{
   // some code
}
}

//Beginning of A2.h
namespace A2   //beginning of a namespace A1
{
class A
{
   // some code
}
}

Now let us see what happens when these two header files are included in a single program.

#include “A1.h”
#include “A2.h”
void main()
{
A1::A   aObj1;   // No error: AObj is an object of the class defined in A1.h under the
                          namespace A1.
A2::A   aObj2;   // No error: AObj is an object of the class defined in A2.h under the
                          namespace A2.
}

Enclosing classes in namespaces prevents pollution of the global name space.

Sometimes qualifying the name of the class with that of the name space can be cumbersome. The ‘using’ directive helps us in solving this problem.

The following example makes it clear.

#include “A1.h”
#include “A2.h”
void main()
{
using namespace A1;
A   aObj1;   // No error: AObj is an object of the class defined in A1.h under the
                       namespace A1. Please note that we have not used any scope resolution
                       operator, it is because of using directive.

A2::A   aObj2;   // No error: AObj is an object of the class defined in A2.h under the
                              namespace A2.


}

Sometimes if the name spaces are too long, short names can be used as aliases for those long names.

namespace X=a_very_very_long_name;
void main()
{
X::A AObj;
}


No comments:

Post a Comment