C++ Notes to Self: Namespaces

C/C++
‘A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it.’ [learn.microsoft.com]
Author

Dennis Chua

Published

March 9, 2017


A namespace is a region in the code where we can declare C++ types. Here we include functions, variables, classes, variables, etc. Any type declared here is invisible outside of the namespace bounds. Essentially C++ namespace is a scoping mechanism for types.

Namespaces orgainize complex code by preventing name clashes among types, leading to better modularization.

    namespace <name> {
        classes, structures, functions, variables, etc.
    }

A namespace can contain any valid C++ type. They can also be nested. We can create a namespace that is nameless, bound only by curly braces. To access types defined in a nameless namespace, we forgoe the namspace qualifier prefix (i.e. <name>::). Nameless namespaces belong to the global namespace.

We “open” a namespace to make all or part of its elements visible outside the namespace boundary.

    using namespace <name>
    // The full name qualifier present the most narrow namespace scope.
    // Only the specified element is visible outside the namespace.
    using namespace <name>::<element>

Opening the entire namespace is not advised because its types and names may clash with other declared types. It’s better to limit this through the scoping qualifier prefix, with the full name qualifier limiting name clashes.


#include <iostream>

// Example of forward declation with namespace. Typically we put 
// the following three namescape declarations in a C++ header file.
namespace Average {
    double Calculate (double x, double y);
}

namespace Basic {
    double Calculate (double x, double y);
}

namespace SortLibrary {
    void QuickSortAlgo() {}
    void MergeSortAlgo() {}
    void InsertionSortAlgo() {}

    bool CompLessOp() { return false; }
    bool CompGreaterOp() { return false; }
}

// From here we define some of the functions we declared. 
// We show two styles of namespace qualifiers.

double Average::Calculate (double x, double y) {
    return (x + y) / 2;
}

namespace Basic {
    double Calculate (double x, double y) {
        return x + y;
    }
}

int main(int argc, char **argv) {

    std::cout << Basic::Calculate(14.30, 0.23) << std::endl;

    using namespace Average;
    std::cout << Calculate(14.30, 0.23) << std::endl;
    std::cout << SortLibrary::CompLessOp() << std::endl;

    return 0;
}