Sams Teach Yourself C++ in 21 Days

(singke) #1

The Standard Namespace std..............................................................................


The best example of namespaces is found in the C++ Standard Library. The Standard
Library is completely encased within the namespace named std. All functions, classes,
objects, and templates are declared within the namespace std.
You have seen code such as the following:
#include <iostream>
using namespace std ;
Now, you know that when you use the usingdirective in this manner that it is pulling
everything in from the named namespace.
Going forward, you should consider it bad form to employ the usingdirective when
using the Standard Library. Why? Because doing so pollutes the global namespace of
your applications with all the names found in the header. Keep in mind that all header
files use the namespace feature, so if you include multiple standard header files and spec-
ify the usingdirective, then everything declared in the headers is in the global name-
space.
You might be noting that most of the examples in this book violate this rule; this action
is not an intent to advocate violating the rule, but it is used for brevity of the examples.
You should use the usingdeclaration instead, as in Listing 18.10.

LISTING18.10 The Correct Way to Use stdNamespace Items
0: #include <iostream>
1: using std::cin ;
2: using std::cout ;
3: using std::endl ;
4: int main( )
5: {
6: int value = 0 ;
7: cout << “So, how many eggs did you say you wanted?” << endl ;
8: cin >> value ;
9: cout << value << “ eggs, sunny-side up!” << endl ;
10: return( 0 ) ;
11: }

So, how many eggs did you say you wanted?
4
4 eggs, sunny-side up!
As you can see, three items from the stdnamespace are used. These are declared
on lines 1–3.

654 Day 18


OUTPUT


ANALYSIS
Free download pdf