C++ Namespaces

WHAT ARE NAMESPACES?

  • In C++, namespaces allow us to group named entities that have global scope into narrower scope giving them namespace scope.
  • It is like a container for identifiers and it put the name of its members in a distinct space so that they don’t conflict with the names in other namespaces or global namespace.
  • Namespaces are used to organize too many classes so that it is easy to handle the application. The class of a namespace can be accessed by using namespacename::classname.

LET US UNDERSTAND NAMESPACE THROUGH AN EXAMPLE:

 
 
 
 
 
 
C++
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream> 
 
using namespace std; 
 
namespace A {   
 
    void sayWelcome() {  
 
        cout<<“Welcome to first namespace”<<endl;         
 
    }   
 
}   
 
namespace B  {   
 
       void sayWelcome() {  
 
           cout<<“Welcome to second namespace”<<endl;  
 
       }   
 
}  
 
int main() 
 
{ 
 
 A::sayWelcome(); 
 
 B::sayWelcome(); 
 
return 0; 
 
} 
 
Output :
 
Welcome to first namespace
Welcome to second namespace

RULES FOR DECLARING NAMESPACE

  • Its declarations appear only at global scope.
  • Its declarations can be nested within another namespace.
  • Its declarations don’t have access specifiers (public or private).
  • In this we do need to give a semicolon after the closing brace of definition.