What is a namespace?

Namespaces provide a way of declaring variables within a program that have similar names​.

It allows users to define functions with the same name as a function in a pre-defined library or used-defined functions within main().

Namespaces can also be used to define classes, variable names, and functions.

svg viewer

Syntax

The following code shows how namespaces can be declared.

  • n_name is the name of the namespace
  • foo is the function name
namespace n_name{
//enter code here
void foo()
{
cout << "This is a user-defined function"<<endl;
}
}

Once the namespace is declared, the scope resolution operator (::) can be used to refer to variables within the namespace.

The following example shows how to refer to the function foo defined in the namespace n_name above.

n_name::foo()

Code

The following code shows a complete example of how to declare the namespace and uses its functions within a program that contains similar functions.

#include <iostream>
using namespace std;
namespace n_name{// namespace declared
int x= 100; // variable x within namespace
void foo() // function foo within namespace
{
//prints the value of x defined within namespace
cout<< "The value of x in namespace is: "<< x <<endl;
}
}
void foo(int x) //function declared
{
//prints the value of x passed within parameters
cout<< "The value of x in main is: " << x << endl;
}
int main() {
// declare variable x
int x = 10;
foo(x); //call function foo
n_name:: foo(); //call function foo defined in namespace
return 0;
}

You can also direct the program to use the assigned namespace as default by making use of the using keyword.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved