Appropriate for individuals who...
Preparing for C++ Interview.
Passionate C++ developers revising C++ concepts.
Syntax:
namespace <name> {
// can contain the followings...
variable, structure, class, function, namespace etc...
}
Why is namespace?
It is used for the following important reasons.
Helps in modularizing the code.
Prevents name clashes.
How to Access the Contents of a Namespace?
global using declarative (opens the entire namespace)
using declarative (opens a specific type)
fully qualified name
Ex: Standard C++ library uses std namespace.
// Opens the entire namespace. cin, cout etc... are available within the scope.
using namespace std;
cout << "Hello C++\n";
or
// Opens specific type. Here std::cout is opened. But other names like cin is not opened.
using namespace std::cout;
cout << "Hello C++\n";
or
std::cout << "Hello C++\n"; // Fully Qualified Name
Notes:
The namespace within the namespace is known as a nested namespace.
Ex:
#include <iostream>
namespace ex {
namespace ex2 {
void fun() { std::cout << "Hello C++\n"; }
}
}
int main() {
ex::ex2::fun(); // calling fun() present in nested namespace.
}
ASSIGNMENT:
Why Global using Declarative is a bad idea? Write in the comment section.
Want to take your C++ skills to the next level? Visit https://www.cppforme.com for resources, tips, and expert advice to help you improve your coding techniques and become a better developer. And if you need additional help or support, feel free to contact me by visiting my site.