Wednesday, 25 March 2015

Creating a namespace in C++ with example code

Creating a namespace in Cpp with example 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.
The namespace is a declarative region that attaches an additional identifier to any names declared inside it. The additional identifier makes it less likely that a name will conflict with names declared elsewhere in the program.

It is possible to use the same name in separate namespaces without conflict even if the names appear in the same translation unit. As long as they appear in separate namespaces, each name will be unique because of the addition of the namespace identifier.
Namespace creation is not much difficult, the creation of a namespace is notably similar to the creation of a class

See the syntax of the namespce
namespace TestNameSpace {

// our declarations and our code starts here


int main() {}

This produces a new namespace containing the enclosed declarations. There are significant differences from class, struct, union and enum, however:

• A namespace definition can appear only at global scope, or nested within another namespace.
• Like class, No terminating semicolon is necessary after the closing brace of a namespace definition
• A namespace definition can be “continued” over multiple header files using a syntax that, for a class, would appear to be a redefinition

The below is the header file code Test1.h
namespace TestNameSpace
extern int iVal;
void TestFun ();
// ...


Write the code for another header file Test2.h
#include " Test1.h"

// Add more names to TestNameSpace

namespace TestNameSpace {

 // NOT a redefinition!

extern int iVal1;

void TestFun2 ();


#include " Test2.h"
int main() {} ///:~

• A namespace name can be aliased to another name, so you don’t have to type an unwieldy name created by a library vendor:

namespace BobsSuperDuperLibrary {

class Widget { /* ... */ };

 class Poppit { /* ... */ };

// ...


 namespace TestLib = MyTestLibrary;

int main() {}

The difference between the class and the namespace is it is not possible to create an instance of a namespace.

No comments: