A namespace in C++ is a way to organize code into logical groups and prevent name conflicts by creating a distinct scope for identifiers such as functions, classes, and variables. It helps in managing libraries and avoiding naming collisions in large projects.
Let's understand this with an analogy:
The Bookstore Analogy
The Books:
Imagine a bookstore that contains books on various subjects. Each book has a unique identifier, a category number, to distinguish it from other books. In this analogy:
Books are like the functions, classes, and variables in C++.
Category numbers are like namespaces.
Sections:
The Bookstore is divided into different sections, each containing books on specific topics. For example:
Mathematics Section
Literature Section
Stories Section
Now let us fit in the example:
The std Namespace as a Section
Think of std namespace as Standard section in that bookstore. It has books such as:
iostream for input and output
vector for dynamic arrays
string for text strings
To use a book from std Section:
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
This above code is similar to saying, "I want to read the book
cout and endl from std section of the bookstore"
Books from only std section:
If you find it tedious to specify the section name every time to borrow book from std section, you can say:
"I will mostly borrow books from std section"
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
Other Sections/Namespace in C++:
Boost Namespace:
The Boost Section contains advanced books that extend the functionality of the standard library.
Books: smart pointers, regular expressions, threads, etc.
#include <boost/shared_ptr.hpp>
#include <iostream>
int main() {
boost::shared_ptr<int> ptr(new int(10));
std::cout << "Value: " << *ptr << std::endl;
return 0;
}
Custom Namespace:
namespace Drawing {
void drawCircle() {
std::cout<< "Drawing a circle"<<std::endl;
}
}
int main() {
GraphicsLib::drawCircle();
return 0;
}
Knowhow
Libraries: <vector>, <iostream>, <string> etc
Namespace: std, boost etc
Functions: cout, cin etc
Top comments (2)
Except for trivial programs, you should never do
using namespace std
.Yes, only for basic cpp problems where we mostly use functions from std namespace