C++: namespace directives

Objectives :

  • File Name : socpe_namespace1.cpp
    Namespace : A namespace behaves  like a class or struct, contains group of public elements, usually used to resolve conflicts the local data-type with global data-type
  • using directive: using namespace std;
    • All the references from "std" will be available.
  • Console Input and Output: The object "console input" or "cin" is type safe; cin>>integer will not accept any string or alphabets and terminate operation.
  • Code: scope_namespace1.txt

Step: 1 Create a source file.

Step: 2 Edit and save Source file

Step: 3 Runtime Views:

a) Enter a string to generate an error. There won't be any out put, as the data type received was not an integer.

b) Entering an integer

Step 4 Brief Discussion:

C++ introduced the concept of namespace, to avoid name conflicts that could surface in an application created as a group effort or importing source codes from another file. With the help of namespace, the name of the variable could reused without loosing it's properties.

As C++ won't allow to duplicate variable names, and that can become as issue when using external or remote applications. The same name in the above scenario, would generate runtime errors. The namespace with resolution operator can resolve such issues and reuse same vocabularies over and again.

As shown in the above example, int n1 was common in two modules, but namespace with resolution operator you can handles those two variables without causing any conflicts.