Namespaces
Prerequisites: Function overloading
A namespace groups related names to avoid collisions between
libraries — std::cout means "cout, from the std namespace,"
the same way a package qualifies a class name in Java.
namespace mymath {
int square(int x) {
return x * x;
}
}
std::cout << mymath::square(4) << std::endl; // 16
Common mistakes
- Writing
using namespace std;at the top of every file — it's common in small examples (this course avoids it, spelling outstd::explicitly instead) but in larger projects it reintroduces exactly the naming collisions namespaces exist to prevent.