CurriculumNamespaces
Namespaces
As programs grow, you end up with many functions and classes. Namespaces let you group related code under a named scope, preventing name collisions between your code and third-party libraries.
01The std:: Namespace
Everything in the C++ Standard Library lives inside the
The two styles below are equivalent. Run both and see the same output.
std namespace. When you write std::cout, you are saying: the cout that lives inside std.The two styles below are equivalent. Run both and see the same output.
main.cpp
Terminal
Waiting for execution...
02Creating Your Own Namespace
You can define your own namespaces to group related functions. This is how libraries like Boost, OpenCV, and Eigen organize their APIs.
Notice how
Notice how
math::add and math::multiply are completely separate from any global add you might have.main.cpp
Terminal
Waiting for execution...
03Namespace Alias
When a namespace name is long (common in libraries), you can create a shorter alias with
This is common when using libraries like
namespace alias = original;.This is common when using libraries like
namespace fs = std::filesystem;.main.cpp
Terminal
Waiting for execution...
04Nested Namespaces & using Declarations
You can import a single name from a namespace with
C++17 allows nested namespaces with the compact
using std::cout; — this is safer than using namespace std; because it only imports one thing, not everything.C++17 allows nested namespaces with the compact
namespace A::B { } syntax.main.cpp
Terminal
Waiting for execution...
AI Tutor
Without namespaces, two libraries defining a function called 'print' would clash. The C++ Standard Library wraps everything in 'std::' to avoid this.