Search Your Topic

config
Wednesday, 21 June 2017 02:54

C++ Namespaces

Written by
Rate this item
(0 votes)

Namespaces in C++ are used to organize too many classes so that it can be easy to handle the application.

For accessing the class of a namespace, we need to use namespacename::classname. We can use using keyword so that we don't have to use complete name all the time.

In C++, global namespace is the root namespace. The global::std will always refer to the namespace "std" of C++ Framework.


C++ namespace Example

Let's see the simple example of namespace which include variable and functions.

 
  1. #include <iostream>  
  2. using namespace std;  
  3. namespace First {    
  4.     void sayHello() {   
  5.         cout<<"Hello First Namespace"<<endl;          
  6.     }    
  7. }    
  8. namespace Second  {    
  9.        void sayHello() {   
  10.            cout<<"Hello Second Namespace"<<endl;   
  11.        }    
  12. }   
  13. int main()  
  14. {  
  15.  First::sayHello();  
  16.  Second::sayHello();  
  17. return 0;  
  18. }  

Output:

Hello First Namespace
Hello Second Namespace

 

C++ namespace example: by using keyword

Let's see another example of namespace where we are using "using" keyword so that we don't have to use complete name for accessing a namespace program.

 
  1. #include <iostream>  
  2. using namespace std;  
  3. namespace First{  
  4.    void sayHello(){  
  5.       cout << "Hello First Namespace" << endl;  
  6.    }  
  7. }  
  8. namespace Second{  
  9.    void sayHello(){  
  10.       cout << "Hello Second Namespace" << endl;  
  11.    }  
  12. }  
  13. using namespace First;  
  14. int main () {  
  15.    sayHello();  
  16.    return 0;  
  17. }  

Output:

Hello First Namespace	

 

 

 

Read 161 times
Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

toshiyas.in

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.