C++ Programming: Objects, RAII and the STL ยท C++ Basics

Namespaces

Namespaces keep names apart: two functions called distance can live side by side.

namespaces.cpp

#include <iostream>

namespace metric {
    double distance(double km) { return km; }
}

namespace imperial {
    double distance(double km) { return km * 0.621; }
}

int main() {
    double a = metric::distance(10);
    double b = imperial::distance(10);    // same name, different namespace
    std::cout << a << " km = " << b << " miles" << std::endl;
    return 0;
}

Step by step

  1. metric::distance picks the function from the metric namespace.
  2. distance() has finished, so its variables are gone. The value it returned, 10, is stored in a.
  3. Same name, different namespace.
  4. distance() has finished, so its variables are gone. The value it returned, 6.21, is stored in b.
  5. It prints 10 km = 6.21 miles.
  6. The method returns 0.
  7. 10 km = 6.21 miles.