Cpp Namespaces
# C++ Namespaces
Consider a situation where there are two students in a class with the same name "Zara". To distinguish them, we need to use some additional information along with their names, such as their home address or their parents' names, etc.
A similar situation arises in C++ applications. For example, you might write a function named `xyz()`, and there might also be an identical function `xyz()` available in another library. In this case, the compiler would be unable to determine which `xyz()` function you are referring to.
Therefore, the concept of **namespaces** was introduced to solve this problem. Namespaces serve as additional information to distinguish between functions, classes, variables, etc., with the same name in different libraries. Using a namespace defines the context. Essentially, a namespace defines a scope.
Let's take an example from a computer system: a folder (directory) can contain multiple subfolders. Each subfolder cannot have files with the same name, but files in different subfolders can have the same name.
!(#)
## Defining a Namespace
A namespace is defined using the keyword **namespace**, followed by the namespace name, as shown below:
namespace namespace_name{// code declarations}
To call a function or variable within a namespace, you need to prefix it with the namespace name, as shown below:
name::code; // code can be a variable or function
Let's see how namespaces define the scope for entities like variables or functions:
## Example
#includeusing namespace std; // first namespace namespace first_space{void func(){cout<<"Inside first_space"<<endl; }}// second namespace namespace second_space{void func(){cout<<"Inside second_space"<<endl; }}int main(){// call function from first namespace first_space::func(); // call function from second namespace second_space::func(); return 0; }
When the above code is compiled and executed, it produces the following result:
Inside first_space
YouTip