What a namespace is
A namespace is a named scope that groups related names. Two names in different namespaces can be the same without clashing. You refer to a name inside a namespace with the scope operator, ::, written as namespace_name::name.
A small example
#include <iostream>
namespace physics {
double speed = 3.0;
}
namespace games {
double speed = 12.5;
}
int main() {
std::cout << physics::speed << "\n"; // prints 3
std::cout << games::speed << "\n"; // prints 12.5
}
Both variables are called speed, but they live in different namespaces, so the program has no clash. physics::speed means the speed inside the physics namespace, and games::speed means the other one. The first value prints as 3 because the default output format drops the trailing zero of 3.0.
Functions work the same way
Namespaces can hold functions as well as variables:
#include <iostream>
namespace math {
int add(int a, int b) {
return a + b;
}
}
int main() {
std::cout << math::add(2, 3) << "\n"; // prints 5
}
The call math::add(2, 3) names the function and the namespace it belongs to.
Can a namespace be split up?
Yes. A namespace can be declared more than once, and each declaration adds names to it. Large libraries use this to spread one namespace across many header files. The standard library’s std namespace is spread across many headers in the same way.
Using a namespace without the prefix
You can skip the prefix with a using directive, such as using namespace math;. The names you bring in can then clash with your own, so this is best kept for small programs. If you searched for what is the function of using namespace std, the short answer is that it lets you skip the prefix for names in a namespace.
std is a namespace too
The standard library uses a namespace called std. std::cout, std::string and std::vector all come from it. If you searched for what does std mean in C++, the short answer is that std is the namespace for the standard library.
Quick summary
- A namespace is a named scope that keeps names from clashing.
- The
::operator picks a name from a namespace. - Namespaces can hold variables, functions and types.
stdis the namespace for the C++ standard library.