Wednesday, November 2, 2011

namespace std

namespace std c++

If you use different modules and/or libraries, you always have the potential for name clashes. This is because modules and libraries might use the same identifier for different things. This problem was solved by the introduction of namespaces into C++. A namespace is a certain scope for identifiers. Unlike a class, it is open for extensions that might occur at any source. Thus, you could use a namespace to define components that are distributed over several physical modules. A typical example of such a component is the C++ standard library, so it follows that it uses a namespace. In fact, all identifiers of the C++ standard library are defined in a namespace called std.

According to the concept of namespaces, you have three options when using an identifier of the C++ standard library:

option 1:
You can qualify the identifier directly. For example, you can write std::ostream instead of ostream. A complete statement might look like this:

std::cout << std::hex << 3.4 << std::endl;

option 2:
You can use a using declaration (see page 17). For example, the following code fragment
introduces the local ability to skip std:: for cout and endl.

using std::cout;
using std::endl;

Thus the example in option 1 could be written like this:

cout << std::hex << 3.4 << endl;

option 3:
You can use a using directive. This is the easiest option. By using a using directive for namespace std, all identifiers of the namespace std are available as if they had been declared globally. Thus, the statement

using namespace std;

allows you to write

cout << hex << 3.4 << endl;

Note:
In complex code this might lead to accidental name clashes or, worse, to different behavior due to some obscure overloading rules. You should never use a using directive when the context is not clear (such as in header files, modules, or libraries).

See Also:
C++ Language Concepts and Sample Codes

No comments:

Post a Comment