namespace and using Keywords

Namespaces were introduced into C++ primarily as a mechanism to avoid naming conflicts between various libraries. The following example illustrates how this is achieved:Every namespace introduces a new scope. By default, names inside a namespace are hidden from enclosing scopes. Selection of a particular name can be achieved using the qualified-name syntax. Namespaces can be nested very much like classes.

#include <stdio.h>

namespace N { struct Object {

virtual char const* name() const { return “Object from N”; } };

}

namespace M { struct Object {

virtual char const* name() const { return “Object from M”; } };

namespace X { // a nested namespace

struct Object: M::Object { // inherit from a class // in the outer space

char const* name() const { return “Object from M::X”; } };

}

}

int main() { N::Object o1; M::Object o2; M::X::Object o3;

printf(“This object is: %s.\n”, o1.name());

printf(“This object is: %s.\n”, o2.name());

printf(“This object is: %s.\n”, o3.name()); return 0;

}

Connections Across Translation Units

If a type, function, or object is declared inside of a namespace, then using that entity will require naming this namespace in some explicit or implicit way; even if the use happens in another translation unit (or source file).

A unique feature of namespaces is that they can be extended. The following example shows this; as well as the connections between a namespace extending across different translation units.

The example also illustrates the concept of unnamed namespaces. These namespaces can only be extended within a translation unit. Unnamed namespaces in different translation units are unrelated; hence their names effectively have internal linkage. In fact, the ANSI/ISO C++ International Standard specifies that using static to indicate internal linkage is deprecated in favor of using namespaces.

#include <stdio.h>

namespace N {

char const* f() { return “f()”; }

}

namespace { // An unnamed namespace char const* f(double);

}// Names in unnamed namespaces are visible in their surrounding scope. // They cannot be qualified since the space has no name.

144 Standardizing Your Code