Making a Library Changes Your Names

Remember the function Initialize(), which was used to prepare cin for throwing exceptions? What if you moved error handling out to a module of its own, and some other library or main program wanted to use that common name? This could be a problem.

You have already seen a way to deal with this possibility: namespaces. That's the solution iostream uses and it will work perfectly for this situation.

The form of a namespace declaration is

namespace namespacename
{
   statements
} ;

Listing 8.3 is the new header file.

Listing 8.3. Header for ErrorHandlingModule
 1: #ifndef ErrorHandlingModuleH
 2: #define ErrorHandlingModuleH
 3:
*4: namespace SAMSErrorHandling
*5: {
 6:    void Initialize(void);
 7:    int HandleNotANumberError(void); // Returns error code
*8: }
 9:
10: #endif

The implementation file appears in Listing 8.4.

Listing 8.4. Implementation for ErrorHandlingModule
  1: #include <iostream>
 *2: #include "ErrorHandlingModule.h"
  3:
 *4: namespace SAMSErrorHandling
 *5: {
  6:    using namespace std;
  7:
  8:    void Initialize(void)
  9:    {
 10:       cin.exceptions(cin.failbit);
 11:    }
 12:
 13:    int HandleNotANumberError(void) // Returns error code
 14:    {
 15:       cerr << "Input error - not a number?" << endl;
 16:
 17:       cin.clear(); // Clear error state from the stream
 18:
 19:       // Eat the bad input so we can pause the program
 20:       char BadInput[5];
 21:       cin >> BadInput;
 22:
 23:       return 1; // An error occurred
 24:    }
*25: }

You can see how the namespace declaration in the header file (lines 4, 5, and 8 of Listing 8.3) wraps the prototypes and how the namespace declaration in the implementation file (lines 4, 5, and 25 of Listing 8.4) wraps all the functions.


Don't forget to go back and add a namespace declaration to the PromptModule header. The namespace there will be SAMSPrompt.

The name you pick for the namespace should be unique and meaningful at the same time. It should also be something that makes sense when joined to the name of the module functions, as you will see later when the calls have been modified to use the namespace as a qualifier to the function names.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.29.171