Namespace |
|
Namespace is the collection of or group of same type of classes. Meaning of this it is collection of same type of entities. |
|
To give a name to collection of classes of same type is known as namespace. Namespaces permit to collection of entities like classes, objects and functions under a name. |
|
This way the global scope can be divided in “sub-scopes”, each one with its own name. |
|
The format of name space is : |
|
namespace identifier |
{ |
entities |
} |
|
Where identifier is any valid identifier and entities is the set of classes, objects and functions that are included within the namespace. For example: |
|
{ |
int i, j ; |
} |
|
In this case, the variables i and j are regular variables declared within a namespace called myName. |
|
In order to contact these variables from outside the myName namespace we have to use the scope operator:: . For example, to access the previous variables from outside it may be write as |
|
general : : i |
genaral : : j |
|
The functionality of namespaces is mostly useful in the case that there is a possibility that a global object or function uses the same identifier as another one, causing redefinition errors. |
|
For Example : |
|
#include |
|
using namespace std; |
|
namespace first |
|
{ |
int num = 5; |
} |
namespace second
|
{ |
double num = 3.1416; |
} |
int main () {
|
cout << first::num << endl; |
cout << second::num << endl; |
return 0 ; |
} |
|
Using |
|
The keyword using is used to introduce a name from a namespace into the current declarative region. Using is a keyword which tells which namespace is being used. |
|
For example: |
|
#include |
|
using namespace std; |
|
namespace firstvalue{ |
|
{ |
int i = 5 ; |
int j =10 ; |
} |
|
namespace secondvalue |
{ |
double i = 3.1416; |
double j = 2.7183; |
} |
int main () { |
using firstvalue::x; |
using secondvalue::y; |
cout << i << endl; |
cout << j << endl; |
cout << firstvalue::j << endl; |
cout << secondvalue::i << endl; |
return 0 ; |
} |
|
Namespace std |
|
As we know namespace is logical collection of same type of entities. In every program there is use of std namespace. These namespace contains the definition of cout, cin etc |
|
Every one files in the C++ standard library announce every one of its entities within the std namespace. |
|
This is reason why we have normally integrated the using namespace std; statement in all programs that used any entity defined in iostream. std stands for standard. |