Namespace provide the space where we can define or declare identifier i.e. variable, method, classes. Using namespace, you can define the space or context in which identifiers are defined i.e. variable, method, classes. In essence, a namespace defines a scope.
A namespace definition begins with the keyword namespace followed by the namespace name as follows:
namespace namespace_name
{
// code declarations i.e. variable (int a;)
method (void add();)
classes ( class student{};)
}
#include <iostream>
using namespace std;
// define first namespace
namespace first_ns
{
void func()
{
cout << "This is from first namespace" << endl;
}
}
// define second namespace
namespace second_ns
{
void func()
{
cout << "This is from second namespace" << endl;
}
}
//using first namespace by default
using namespace first_ns;
int main ()
{
//calls function from first namespace
func();
return 0;
}
Inside first_space
Namespaces can be nested where you can define one namespace inside another name space as follows:
SYNTAX:
namespace namespace_name1
{
// code declarations
namespace namespace_name2
{
// code declarations
}
}
You can access members of nested namespace by using resolution operators as follows:
// to access members of namespace_name2
using namespace namespace_name1::namespace_name2;
// to access members of namespace_name1
using namespace namespace_name1;
In the above statements if you are using namespace_name1, then it will make elements of namespace_name2 available in the scope as follows:
#include <iostream>
using namespace std;
// first namespace
namespace first
{
void func()
{
cout << "Inside first namespace" << endl;
}
// second namespace nested inside first
namespace second
{
void func()
{
cout << "Inside second namespace" << endl;
}
}
}
// using directive to access nested namespace
using namespace first::second;
int main()
{
// This calls the function from the second namespace
func();
return 0;
}
Inside second_space
How namespace scope the entities including variable and functions:
#include <iostream>
using namespace std;
// First namespace
namespace first_ns {
void func() {
cout << "Inside first namespace" << endl;
}
}
// Second namespace
namespace second_ns {
void func() {
cout << "Inside second namespace" << endl;
}
}
int main() {
// Calls function from first namespace
first_ns::func();
// Calls function from second namespace
second_ns::func();
return 0;
}
Output
Inside first_space
Inside second_space
// A program to demonstrate need of namespace
int main()
{
int value;
value = 0;
double value; // Error here
value = 0.0;
}
Compiler Error:
'value' has a previous declaration as 'int value'
In each scope, a name can only represent one entity. So, there cannot be two variables with the same name in the same scope. Using namespaces, we can create two variables or member functions having the same name.
#include <iostream>
using namespace std;
// Variable created inside namespace
namespace first {
int val = 500;
}
// Global variable
int val = 100;
int main()
{
// Local variable
int val = 200;
// These variables can be accessed from
// outside the namespace using the scope
// operator ::
cout << first::val << '\n';
return 0;
}
The output of this code is '500'. This is because we are accessing the val variable inside the first namespace using the scope resolution operator '::'. This allows us to differentiate between variables with the same name declared in different scopes or namespaces. In this case, the val inside the first namespace has a value of 500, while the global val has a value of 100 and the local val inside the main function has a value of 200.
Output
500
Definition and Creation: Namespaces allow us to group named entities that otherwise would have global scope into narrower scopes, giving them namespace scope. This allows organizing the elements of programs into different logical scopes referred to by names. Namespaces provide the space where we can define or declare identifiers i.e. names of variables, methods, classes, etc.
A namespace definition begins with the keyword namespace followed by the namespace name as follows:
namespace namespace_name
{
int x, y; // code declarations where
// x and y are declared in
// namespace_name's scope
}
A namespace definition begins with the keyword namespace followed by the namespace name as follows:
namespace namespace_name{
// code declarations i.e. variable (int a;)
method (void add();)
classes ( class student{};)
}
It is to be noted that there is no semicolon (;) after the closing brace.
To call the namespace-enabled version of either a function or a variable, prepend the namespace name as follows:
namespace_name: :code; // code could be a variable, function or class.
#include <iostream>
using namespace std;
// namespace for mathematical operations
namespace math_ops
{
int add(int a, int b)
{
return a + b;
}
int multiply(int a, int b)
{
return a * b;
}
}
// namespace for string operations
namespace string_ops
{
string concat(string s1, string s2)
{
return s1 + s2;
}
int length(string s)
{
return s.length();
}
}
int main ()
{
// Using math_ops namespace
int sum = math_ops::add(5, 6);
int product = math_ops::multiply(3, 4);
cout << "Sum: " << sum << endl;
cout << "Product: " << product << endl;
// Using string_ops namespace
string s1 = "Hello";
string s2 = "World";
string s3 = string_ops::concat(s1, s2);
int s3_length = string_ops::length(s3);
cout << "Concatenated string: " << s3 << endl;
cout << "Length of the string: " << s3_length << endl;
return 0;
}
// Sum: 11
// Product: 12
// Concatenated string: HelloWorld
// Length of the string: 10
You can avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace. The namespace is thus implied for the following code:
#include <iostream>
using namespace std;
// namespace for mathematical operations
namespace math_ops
{
int add(int a, int b)
{
return a + b;
}
int subtract(int a, int b)
{
return a - b;
}
}
// namespace for string operations
namespace string_ops
{
string concat(string s1, string s2)
{
return s1 + s2;
}
int length(string s)
{
return s.length();
}
}
using namespace math_ops;
int main ()
{
// This calls the add function from math_ops namespace.
int sum = add(5, 6);
cout << "Sum: " << sum << endl;
// This calls the subtract function from math_ops namespace.
int difference = subtract(10, 4);
cout << "Difference: " << difference << endl;
return 0;
}
Inside first_space
Instead of accessing the whole namespace, another option (known as using declaration) is to access a particular item within a namespace. For example, if the only part of the std namespace that you intend to use is cout, you can refer to it as follows:
using std::cout;
Subsequent code can refer to cout without prepending the namespace, but other items in the std namespace will still need to be explicit as follows:
#include <iostream>
using std::cout;
int main ()
{
// Here we use "std::endl" with "std" namespace to output a message on the console.
cout << "std::endl is used with std!" << std::endl;
return 0;
}
std::endl is used with std!
Names introduced in a using directive obey normal scope rules, i.e., they are visible from the point the using directive occurs to the end of the scope in which the directive is found. Entities with the same name defined in an outer scope are hidden.
#include <iostream>
using namespace std;
namespace ns1 {
int value() {
return 5;
}
} // namespace ns1
namespace ns2 {
const double x = 100;
double value() {
return 2 * x;
}
} // namespace ns2
int main()
{
// Access value function within ns1
cout << ns1::value() << '\n';
// Access value function within ns2
cout << ns2::value() << '\n';
// Access variable x directly
cout << ns2::x << '\n';
return 0;
}
5
200
100
The following is a simple way to create classes in a namespace:
#include <iostream>
using namespace std;
namespace custom
{
// A class defined inside the custom namespace
class Person
{
public:
void introduce()
{
cout << "custom::Person::introduce()" << endl;
}
};
}
int main()
{
// Creating an object of Person class
custom::Person p;
// Invoking the introduce() method of Person class
p.introduce();
return 0;
}
custom::Person::introduce()
A class can also be declared inside namespace and defined outside namespace using the following syntax:
#include <iostream>
using namespace std;
namespace custom {
// Forward declaration of the class geek inside the custom namespace
class geek;
} // namespace custom
// Definition of the geek class outside the custom namespace
class custom::geek {
public:
void printMessage() { cout << "custom::geek::printMessage()\n"; }
};
int main()
{
// Creating an object of the geek class
custom::geek obj;
// Invoking the printMessage() method of the geek class
obj.printMessage();
return 0;
}
custom::geek::printMessage()
We can define methods as well outside the namespace. The following is an example code:
#include <iostream>
using namespace std;
// Creating a namespace
namespace myns {
void show();
class student {
public:
void show();
};
} // namespace myns
// Defining methods of namespace
void myns::student::show() {
cout << "myns::student::show()\n";
}
void myns::show() {
cout << "myns::show()\n";
}
// Driver code
int main() {
myns::student obj;
myns::show();
obj.show();
return 0;
}
// myns::show()
// myns::student::show()
Namespaces can be nested, i.e., you can define one namespace inside another namespace as follows:
namespace namespace_name1 {
// code declarations
namespace namespace_name2 {
// code declarations
}
}
You can access the members of a nested namespace by using the resolution operator (::) as follows:
// to access members of namespace_name2
using namespace namespace_name1::namespace_name2;
// to access members of namespace:name1
using namespace namespace_name1;
In the above statements, if you are using namespace_name1, then it will make the elements of namespace_name2 available in the scope as follows:
#include <iostream>
using namespace std;
// Define a namespace named "animal"
namespace animal {
// Define a namespace named "mammal" inside the namespace "animal"
namespace mammal {
void sound() {
cout << "Mammals produce sounds.\n";
}
}
}
// Using directive to access the "mammal" namespace inside "animal" namespace
using namespace animal::mammal;
// Driver code
int main () {
// This calls function from "mammal" namespace inside "animal" namespace.
sound();
return 0;
}
Mammals produce sounds.
For example, you might be writing some code that has a function called xyz() and there is another library available in your code which also has the same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.
70 videos|45 docs|15 tests
|
|
Explore Courses for Software Development exam
|