- Namespaces
- A Brief Historical Background
- Properties of Namespaces
- Interaction with Other Language Features
- Conclusions
Interaction with Other Language Features
Namespaces interact with other features of the language and affect programming techniques. They make some features in C++ superfluous or undesirable, as I will show below.
Using the Scope Resolution Operator
In some frameworks, it's customary to add operator :: before a function's name in order to mark it explicitly as a function that is not a class member. For example:
void C::fill (const char * source) { ::strcpy (this->pbuf, source); }
This practice is not recommended, though. Many of the standard functions that used to be global are now declared in namespaces. For example, strcpy now belongs to namespace std, as do most of the Standard Library's functions. Adding the preceding :: to these functions might confuse the compiler's lookup algorithm and mislead human readers. Therefore, you should use either the function's fully qualified name or an appropriate using-declaration when referring to such a function.
Using static to Indicate Internal Linkage
In standard C, a nonlocal identifier that is declared static has internal linkage, which means that it's accessible only from the translation unit in which it is declared. This technique is used to support information hiding, as in the following example:
//File hidden.c static void decipher(FILE *f);/* //invisible from other files */ decipher (“passwords.bin”); //end of file
Although this convention is still supported in C++, it is now considered deprecated. This means that future releases of your compiler might issue a warning message if you declare a nonlocal variable to be static. In order to make a function accessible only from within its translation unit, use an unnamed namespace instead. You should do that, for instance, when you migrate from C. Consider the following example:
//File hidden.cpp namespace //unnamed { void decipher(FILE *f); } /* now use the function in hidden.cpp. No using declarations or directives are needed */ decipher ("passwords.bin");
Members of an unnamed namespace can never be seen from any other translation unit, so the net effect is as if they had static linkage. If you declare another function with the same name in an unnamed namespace in another file, the two functions will not clash.
Names of Standard Header Files
All standard C++ header files now have to be included in the following way:
#include//note: no “.h” extension
That is, the ".h" extension is omitted. This convention also
applies to the standard C header files, with the addition of the letter
'c' affixed to their name. Thus, a C standard header formerly named
#include//formerly:
Although the older convention for C headers (i.e.,
#includeusing std::printf; void f() { printf("Hello World"); }