The Concept of Namespaces
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.
So, what exactly 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, of course. 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 Listing 2.2 will help you avoid this repetition.
Listing 2.2. 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: }
Listing 2.3. 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: }