Saturday, November 5, 2011

Use of namespace in c++

From Professional C++ 2nd edition:
Namespaces address the problem of naming conflicts between different pieces of code.
#include "namespaces.h"
#include <iostream>
namespace mycode {
    void foo() {
        std::cout << "foo() called in the mycode namespace" << std::endl;
    }
}
To call the namespace-enabled version of foo(), prepend the namespace onto the function name by using :: also called the scope resolution operator as follows.
mycode::foo();    // Calls the "foo" function in the "mycode" namespace

You can also avoid prepending of namespaces with the using directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace.

A single source file can contain multiple using directives, but beware of overusing this shortcut. In the extreme case, if you declare that you’re using every namespace known to humanity, you’re effectively eliminating namespaces entirely!

The using directive can also be used to refer to a particular item within a namespace. For example, if the only part of the std namespace that you intend to use is cout, you can refer to it as follows:
using std::cout;

Subsequent code can refer to cout without prepending the namespace, but other items in the std namespace will still need to be explicit:
using std::cout;

cout << "Hello, World!" << std::endl;

No comments:

Post a Comment