Namespaces in C++
C++ Namespaces
In C++, a namespace is a container for identifiers (i.e. names of types, functions, variables, etc.). It is used to organize code and prevent naming conflicts. Namespaces are defined using the namespace keyword, and an identifier is added to a namespace using the scope resolution operator (::). Let us learn everything about namespaces in C++ over here.
Namespaces in C++
To access an identifier in a namespace, you use the scope resolution operator. For example, to call the print_x function in the my_namespace namespace, you would use my_namespace::print_x();
You can also use using namespace directive to make all the identifiers in a namespace available without the need to qualify them with the namespace name.
using namespace my_namespace; print_x();
For example:
namespace my_namespace {
int x = 5;
void print_x() {
cout << x << endl;
}
}
Namespace in C++
// A C++ program to demonstrate use of class
// in a namespace
#include <iostream>
using namespace std;
namespace ns
{
// A Class in a namespace
class prepster
{
public:
void display()
{
cout<<"ns::prepster::display()"<<endl;;
}
};
}
int main()
{
// Creating Object of prepster Class
ns::prepster obj;
obj.display();
return 0;
}
Output
ns::prepster::display()
There are several ways to use a namespace in C++:
Using the scope resolution operator (
::) to access identifiers within a namespace. For example, if you have a variablexin a namespacemy_namespace, you can access it by usingmy_namespace::x.Using the
usingdirective to bring all identifiers from a namespace into the current scope. For example, if you want to use all identifiers in themy_namespacenamespace, you can useusing namespace my_namespace;.Using the
usingdeclaration to bring a specific identifier from a namespace into the current scope. For example, if you want to use only thexvariable in themy_namespacenamespace, you can useusing my_namespace::x;.
It’s important to note that it’s a best practice to be explicit about what symbols you’re importing and where they come from, instead of using using namespace in header files, as it can lead to naming conflicts and make code harder to understand.
It’s also important to note that, when you use using directive it will make all the identifiers in a namespace available without the need to qualify them with the namespace name, and if you have same identifier in different namespace, it will lead to naming conflict.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Login/Signup to comment