Topic 81 of 83
Namespaces
Overview
Namespaces group entities like classes, objects, and functions under a name. This prevents naming conflicts (collisions) when combining multiple libraries that might use the same names (like two libraries both having a Vector class).
Syntax
cpp
namespace PhysicsLib {
double gravity = 9.81;
void print() { cout << "Physics"; }
}
namespace MathLib {
double pi = 3.14;
void print() { cout << "Math"; }
}
int main() {
cout << PhysicsLib::gravity;
MathLib::print();
}Common Pitfalls
- Putting
using namespace xxx;inside a.hheader file. It forces every single.cppfile that includes your header to pollute its namespace.
Interview Questions
- Be ready to explain why
using namespace std;is generally forbidden in professional codebases. It pulls hundreds of standard library names into the global scope, increasing the chance of name collisions.
Real-World Example
Resolving conflicts without 'using namespace'.
example
cpp
#include <iostream>
#include <string>
// Notice no 'using namespace std;'
int main() {
std::string name = "Kartik";
std::cout << "Hello, " << name << std::endl;
return 0;
}