Sams Teach Yourself C++ in 21 Days

(singke) #1
Creating and Using Namespaces 655

18


As an alternative, you could fully qualify the names that you use, as in Listing 18.11.

LISTING18.11 Qualifying Namespace Items Inline


0: #include <iostream>
1: int main( )
2: {
3: int value = 0 ;
4: std::cout << “How many eggs did you want?” << std::endl ;
5: std::cin >> value ;
6: std::cout << value << “ eggs, sunny-side up!” << std::endl ;
7: return( 0 ) ;
8: }

How many eggs did you want?
4
4 eggs, sunny-side up!
Qualifying namespace items inline might be appropriate for shorter programs but
can become quite cumbersome for any significant amount of code. Imagine hav-
ing to prefix std::for every name you use that is found in the Standard Library!

Summary ..............................................................................................................


Today’s lesson expanded on information you have been previously exposed to throughout
this book.
Creating a namespace is very similar to a class declaration. A couple of differences are
worth noting. First, a semicolon does not follow a namespace’s closing brace. Second, a
namespace is open, whereas a class is closed. This means that you can continue to define
the namespace in other files or in separate sections of a single file.
Anything that can be declared can be inserted into a namespace. If you are designing
classes for a reusable library, you should be using the namespace feature. Functions
declared within a namespace should be defined outside of that namespace’s body. This
promotes a separation of interface from implementation and also keeps the namespace
from becoming cluttered.
The usingdirectiveis used to expose all names in a namespace into the current scope.
This effectively fills the global namespace with all names found in the named name-
space. It is generally bad practice to use the usingdirective, especially with respect to
the Standard Library. Use usingdeclarationsinstead.
A usingdeclaration is used to expose a specific namespace item into the current scope.
This allows you to refer to the object by its name only.

OUTPUT


ANALYSIS
Free download pdf