info@tutsfinder.in



Namespaces


Namespace is used to create two variables and member functions with same name, it’s main purpose is to prevent ambiguity that may occur when two variable shaving have same name.

Synatx –

 
namespace namespace_name 
{
   int x, y; /* code declarations where 
              x and y are declared in 
              namespace_name's scope*/
}

Namespace Example :



#include <iostream> 
using namespace std;  

namespace Tuts {    
    void Hello() {   
        cout << "Hello World" << endl;          
    }    
}    
namespace Finder  {    
       void Hello() {   
           cout << "Java Tutorials" << endl;   
       }    
}   
int main()  
{  
 Tuts::Hello();  
 Finder::Hello();  
return 0;  
}


Output:

Hello World
Java Tutorials


Nested namespace in C++

Defining a namespace inside another namespace

namespace namespace_name1
{
    body of namespace_name1
    ... ... ...
    namespace namespace_name2
    {
        body of namespace_name2
    }
    ... ... ...
}


Program to show nested namespace:

#include <iostream>
#include <conio.h>
using namespace std;

namespace first
{
    int a;
    float b;
    namespace second
    {
        float add(int x, float y)
        {
            return x+y;
        }
    }
}

int main()
{
    cout << "Enter a and b: ";
    cin >> first::a >> first::b;
    cout << "Sum = " << first::second::add(first::a,first::b) << endl;
    getch();
    return 0;
}


Output:

Enter a and b: 45
23
Sum = 68