Namespaces in C++ are used to organize an excessive number of classes for easier handling of applications.
To access classes within a namespace, we need to use namespacename::classname. We can also use the using keyword, so we don’t have to keep using the full name.
In C++, the global namespace is the root namespace. global::std always refers to the std namespace of the C++ framework.
👇 Click to Claim 👇
👉 C Language Knowledge Resource Collection
C++ Namespace Example
Let’s look at a simple example of a namespace that contains variables and functions.
#include <iostream>
using namespace std;
namespace First { void sayHello() { cout << "Hello First Namespace" << endl; }}
namespace Second { void sayHello() { cout << "Hello Second Namespace" << endl; }}
int main() { First::sayHello(); Second::sayHello(); return 0;}
Output:
Hello First Namespace
Hello Second Namespace
C++ Namespace Example: Using Keyword
Let’s look at another example of a namespace where we used the using keyword, so we don’t have to use the full name to access the program within the namespace.
#include <iostream>
using namespace std;
namespace First { void sayHello() { cout << "Hello First Namespace" << endl; }}
namespace Second { void sayHello() { cout << "Hello Second Namespace" << endl; }}
using namespace First;
int main() { sayHello(); return 0;}
Output:
Hello First Namespace
Popular Recommendations
-
CLion Tutorial – Makefile Projects in CLion
-
C Language Algorithms – “Gray Code” Algorithm Problem
-
C++ Tutorial – Detailed Explanation of Data Abstraction in C++