🧭 C++ Namespaces – Avoid Name Clashes with Ease
Ever got confused when two functions or variables had the same name? That’s where namespaces come to the rescue!
Namespaces group your code and avoid naming conflicts, especially in large projects or libraries.
🧪 What is a Namespace?
A namespace is like a label or container that helps organize functions, variables, and classes.
You can create your own namespace like this:
#include <iostream> using namespace std; namespace coolspace { void greet() { cout << "Hello from coolspace!" << endl; } } int main() { coolspace::greet(); // Using the function from namespace return 0; }
🚀 Using using namespace
To avoid writing the namespace every time, you can do this:
#include <iostream> using namespace std; using namespace coolspace; namespace coolspace { void greet() { cout << "No need to use prefix now!" << endl; } } int main() { greet(); // No need to write coolspace::greet() return 0; }
📦 Built-in Namespace: std
In C++, the std
namespace contains all the standard library features like cout
, cin
, etc.
You’ve probably used this already:
using namespace std;
But you can also do:
std::cout << "Hello!" << std::endl;
✅ Summary
- Namespaces prevent naming conflicts.
- Use
::
to access namespaced items. using namespace
can simplify code but use with care in large projects.