Namespaces

suggest change

Introduction

Used to prevent name collisions when using multiple libraries, a namespace is a declarative prefix for functions, classes, types, etc.

Syntax

Remarks

The keyword namespace has three different meanings depending on context:

  1. When followed by an optional name and a brace-enclosed sequence of declarations, it defines a new namespace or extends an existing namespace with those declarations. If the name is omitted, the namespace is an unnamed namespace.
  2. When followed by a name and an equal sign, it declares a namespace alias.
  3. When preceded by using and followed by a namespace name, it forms a using directive, which allows names in the given namespace to be found by unqualified name lookup (but does not redeclare those names in the current scope). A using-directive cannot occur at class scope.

using namespace std; is discouraged. Why? Because namespace std is huge! This means that there is a high chance that names will collide:

//Really bad!
using namespace std;

//Calculates p^e and outputs it to std::cout
void pow(double p, double e) { /*...*/ }

//Calls pow
pow(5.0, 2.0); //Error! There is already a pow function in namespace std with the same signature,
               //so the call is ambiguous

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Namespaces:
* Namespaces

Table Of Contents
8 Arrays
11 Loops
39 Streams
51 Unions
53 Namespaces
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype