Namespaces
A namespace is a named scope. By grouping related declarations in a namespace, you can avoid name collisions with declarations in other namespaces. For example, suppose you are writing a word processor, and you use packages that others have written, including a screen layout package, an equation typesetting package, and an exact-arithmetic package for computing printed positions to high accuracy with fixed-point numbers.
The equation package has a class called fraction
, which represents built-up fractions
in an equation; the arithmetic package has a class called fraction
, for computing with exact rational
numbers; and the layout package has a class called fraction
for laying out fractional regions of
a page. Without namespaces, all three names would collide, and you would not be able to use more
than one of the three packages in a single program.
With namespaces, each class can reside in a separate namespace—for
example, layout::fraction
, eqn::fraction
, and math::fraction
.
Tip
C++ namespaces are similar to Java packages, with a key difference: in Java, classes in the same package have additional access rights to each other; in C++, namespaces confer no special access privileges.
Namespace Definitions
Define a namespace with the namespace
keyword followed by an optional identifier (the namespace name) and zero or more declarations in curly braces. Namespace declarations can be discontiguous, even in separate source files or headers. The namespace scope is the accumulation ...
Get C++ In a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.