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 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
Loading...
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 math::add and math::multiply are completely separate from any global add you might have.
main.cpp
Loading...
Terminal
Waiting for execution...

03Namespace Alias

When a namespace name is long (common in libraries), you can create a shorter alias with namespace alias = original;.

This is common when using libraries like namespace fs = std::filesystem;.
main.cpp
Loading...
Terminal
Waiting for execution...

04Nested Namespaces & using Declarations

You can import a single name from a namespace with 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
Loading...
Terminal
Waiting for execution...
← Back to Curriculum