logo

C++ namespaces and the 'using' directive

Reference: "Migrating to Namespaces," Dr. Dobb's Journal, October 2000, pp. 48-52.

The final version of the C++ standard defines names from system header files in a "namespace" called std. The standard requires that you specify which names in a standard header file you'll be using. While most compilers now accept the new format, they don't require it. Subsequent versions will make this syntax mandatory, so you should begin using it now. The Deitel textbook conforms to the standard for C++ header files, but not for C header files.

As an example, the following code was formerly acceptable C++ but is invalid under the latest standard:

#include <iostream.h>
int main()
{
   cout << "Hello, world!" << endl;
}

The following three examples show how the C++ standard would now represent this code.

// Option 1
#include <iostream>
 
int main()
{
   std::cout << "Hello, world!" << std::endl;
}
 
// Option 2
#include <iostream>
using std::cout;
using std::endl;
 
int main()
{
   cout << "Hello, world!" << endl;
}
 
// Option 3
#include <iostream>
using namespace std;
 
int main()
{
   cout << "Hello, world!" << endl;
}

For all of these, notice that the ".h" extension on the name of the system header file is omitted. You would still include the ".h" extension for any header file you write, but the extension is omitted for system header files. The second option above is the preferred option, and is the one that is used in the Deitel textbook. Don't include using directives in your header files unless the name you are specifying is actually used in the header file. In most cases the using directive will appear in the implementation file. When you include a system header file, you should indicate which specific names are defined in the header file that you will be using in your program. If you are including multiple system header files, you should put the appropriate using directives after each header files. The following is a rewritten version of the implementation file found in Figure 8.5 of the Deitel text (page 5480 in 3rd edition), incorporating these suggestions:

#include <iostream>
using std::cout;
using std::endl;
 
#include <iomanip>
using std::setw;
 
#include <cstring>
using std::strcpy;   // Omit this line for Visual C++
using std::strcat;   // Omit this line for Visual C++
 
#include <cassert>
using std::assert;   // Omit this line for Visual C++
 
#include "string1.h"

Put C++ system header files with their using directives first. Any C header files come next. Notice that header files that are holdovers from the C language begin with the letter "c" and omit the ".h" extension. The header file formerly referred to as is now . Microsoft Visual C++ (version 6 and earlier) doesn't allow using directives with C header files, but this problem is fixed started with version 7. The Deitel text omits using directives for C header files to be consistent with Visual C++.