Consider a scenario in which two students with the same name, Laura, are enrolled in the same class. Whenever we need to distinguish them, we will have to utilise some additional information in addition to their names, such as the location they live in if they live in different areas, their mother’s or father’s name, and so on.
The same scenario can occur in your C++ program. For example, suppose you’re building some code with a function called xyz(), and you discover that another library contains the same method xyz(). Now the compiler has no idea which version of the xyz() function you’re talking about in your code.
A namespace in C++ is used as additional information to distinguish similar functions, classes, variables, and other items with the same name that are available in various libraries. You can define the context in which names are defined by using namespace. A namespace, in essence, specifies a scope.
Defining a Namespace:
A namespace definition starts with the keyword namespace and then the namespace name, as shown below:
namespace namespace_name {
// code declarations
}
To invoke the namespace-enabled version of a function or variable, append (::) the namespace name to the function or variable name like follows:
name::code; // code could be variable or function.
Now Lets see an example:
#include <iostream> using namespace std; namespace namespace_1 { void func() { cout << "Namespace 1" << endl; } } namespace namespace_2 { void func() { cout << "Namespace_2"; } } // namespace namespace_2 int main() { namespace_1::func(); namespace_2::func(); return 0; }
Output:
Namespace 1
Namespace_2
Let’s see another example:
#include <iostream> using namespace std; namespace circle_area_int { void area_func(int r) { cout << "Area of circle: " << 3.14 * r * r << endl; } } namespace circle_area_float { void area_func(float r) { cout << "Area of circle: " << 3.14 * r * r << endl; } } int main() { circle_area_int::area_func(2); circle_area_float::area_func(2.3); return 0; }
Output:
Area Of Circle:
Area Of Circle:
Join Our Community
Join our WhatsApp Group To know more about Programming Language tips, tricks and knowledge about and how to start learning any programming language.
Related Articles: