Tuesday, May 6, 2014

The concept of namespaces in C++

The concept of namespaces in C++


The reason you used std::cout in the program and not only cout is that the artifact (cout) that you want to invoke is in the standard (std) namespace.

What are namespaces ?

Assume that you didn’t use the namespace qualifier in invoking cout and assume that cout existed in two locations known to the compiler - which one should the compiler invoke ? 
This causes a conflict and the compilation fails. This is where namespaces get useful. Namespaces are names given to parts of code that help in reducing the potential for a naming conflict. By invoking std::cout, you are telling the compiler to use that one unique cout that is available in the std namespace.

Many programmers find it tedious to repeatedly add the std namespace specifier to their code when using cout and other such features contained in the same. The using namespace declaration as demonstrated in Example 1.1 will help you avoid this repetition.

Example 1.1: The using namespace declaration

1: // Pre-processor directive
2: #include <iostream>
3:
4: // Start of your program
5: int main()
6: {
7: // Tell the compiler what namespace to search in
8: using namespace std;
9:
10: // Write to the screen using std::cout 
11: cout << “Hello World” << endl;
12:
13: // Return a value to the OS
14: return 0;
15: }


Note: By telling the compiler that you are using the namespace std, you don’t need to explicitly mention the namespace on Line 11 when using std::cout or std::endl.

A more restrictive variant of Example 1.1 is shown in Example 1.2 where you do not include a namespace in its entirety. You only include those artifacts that you wish to use.

Example 1.2: Another demonstration of the using keyword

1: // Pre-processor directive
2: #include <iostream>
3:
4: // Start of your program
5: int main()
6: {
7: using std::cout;
8: using std::endl;
9:
10: /* Write to the screen using cout */
11: cout << “Hello World” << endl;
12:
13: // return a value to the OS
14: return 0;
15: }


Note: Line 8 in Example 1.1 has now been replaced by Lines 7 and 8 in Example 1.2. The difference between using namespace std and using std::cout is that the former allows all artifacts in the std namespace to be used without explicitly needing to specify the namespace qualifier std::. With the latter, the convenience of not needing to disambiguate the namespace explicitly is restricted to only std::cout and std::endl.

No comments:

Post a Comment