Namespaces group names and prevent collisions. The standard library lives in std—hence std::vector, std::cout.
Using declarations
using std::cout;
cout << "Only cout imported\n";
namespace utils {
int doubleValue(int x) { return x * 2; }
}
Avoid using namespace std; in headers—it pollutes every file that includes yours.
Important interview questions and answers
- Q: Why std:: prefix?
A: Identifies standard library entities and avoids clashes with user code. - Q: Anonymous namespaces?
A: Give internal linkage to helpers in a .cpp file—likestaticat file scope.
Self-check
- Why avoid using namespace std in headers?
- What does namespace utils::doubleValue mean?
Pitfall: using namespace std; in headers causes name clashes for every includer—keep it in small .cpp files only if at all.
Interview prep
- Why std:: prefix?
Identifies standard library entities and prevents name collisions with user code.
- using namespace std in headers?
Discouraged—it injects all std names into every translation unit that includes the header.