Suppose we’re organizing a concert. There are different areas within the event place. There's a staging area for performances, a food court area for dining, and a lounge area for relaxation.
Let’s assign a name to each area to keep things organized:
The stage area is named as a stage.
The food court area is named as food court.
The lounge area is named as lounge.
In programming, namespaces serve a similar purpose. They’re like named areas where we can group related code together. Each namespace has a unique name, just like each area at the event venue.
Note: The
std
namespace is a standard namespace that contains many standard C++ functions and objects.
Let’s create a customized namespace in the code below:
#include <iostream>// Define a custom namespace called MyNamespacenamespace MyNamespace {// Declare a function called myFunctionvoid myFunction() {std::cout << "Hello from MyNamespace!" << std::endl;}}int main() {// Call myFunction from MyNamespaceMyNamespace::myFunction();return 0;}
Line 4–9: We define a namespace called MyNamespace
and a function called myFunction()
inside that namespace.
Line 13: We call myFunction()
using the scope resolution operator ::
to specify that we’re calling myFunction()
from MyNamespace
.
Namespace collisions can occur when two namespaces have elements (like functions, variables, or classes) with the same name. This can happen if we’re using multiple libraries or if we define our own namespaces with conflicting names.
Let’s create an example to illustrate this collision below:
#include <iostream>// First namespacenamespace FirstNamespace {void display() {std::cout << "Hello from FirstNamespace!" << std::endl;}}// Second namespace with a conflicting namenamespace SecondNamespace {void display() {std::cout << "Hello from SecondNamespace!" << std::endl;}}int main() {// Attempt to call display() without specifying the namespacedisplay(); // This will result in a compilation error due to ambiguity// To fix the issue, we need to specify which display() function to call// and comment the above display() callFirstNamespace::display();SecondNamespace::display();return 0;}
Line 4–15: We have two namespaces (FirstNamespace
and SecondNamespace
), each containing a display()
function.
Line 19: When we try to call display()
without specifying the namespace display()
, the compiler doesn’t know which display()
function to use, leading to a compilation error.
Line 22–23: To fix this, we need to specify the namespace for each display()
call. This tells the compiler exactly which display()
function to use.
Free Resources