C++ Namespaces


In C++ namespaces are used to sort too many classes so that it helps to handle the application.

The global::std refer to the namespace "std".


Defining a Namespace

A namespace definition starts with the keyword namespace.

Syntax:

namespace namespace_name {
   // code declarations
}

Example:

#include <iostream> 
using namespace std;  

namespace first {    
    void welcome() 
    {   
        cout << "Welcome To First Namespace" << endl;          
    }    
}    
namespace second  {    
    void welcome() 
    {   
        cout << "Welcome To Second Namespace" << endl;   
    }    
} 
namespace third  {    
    void welcome() 
    {   
        cout << "Welcome To Third Namespace" << endl;   
    }    
} 
int main()  
{  
    first::welcome(); // Calls function from first namespace.
    second::welcome(); // Calls function from second namespace.
    third::welcome(); // Calls function from third namespace.
    return 0;  
}  

The Using namespace directive

The Using namespace directive helps to avoid prefix of namespaces.

Example:

#include <iostream> 
using namespace std;  

namespace first {    
    void welcome() 
    {   
        cout << "Welcome To First Namespace" << endl;          
    }    
}    
namespace second  {    
    void welcome() 
    {   
        cout << "Welcome To Second Namespace" << endl;   
    }    
} 
namespace third  {    
    void welcome() 
    {   
        cout << "Welcome To Third Namespace" << endl;   
    }    
} 
using namespace third;
int main()  
{  
    welcome(); 
    return 0;  
}



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.