C++ Basic Programming 5

Namespace

Namespaces allows us to group named entities that otherwise would have a global scope into narrower scopes, giving them namespace scope. This allows organizing the elements of a program into different logical scopes referred to by names.

• Namespace is a feature added in C++ and not in C.
• A namespace is a declarative region that provides a scope to the identifiers( names of the types, functions, variables etc) inside it.
• Multiple namespace blocks can have variable with same name.
• All the declarations within those blocks are declared in the named scope.

A namespace definition begins with the keyword “namespace” followed by the namespace name as follows:

namespace abc
{
int a=10;
int b=20;
}
namespace xyz
{
int a=100;
int b=200;
}

 

• Namespace declaration appears only at global scope
• Namespace declaration can be nested within another namespace
• Namespace declarations don’t have access specifiers (public or private)
• No need to give semicolon after the closing brace of definition of namespace.

Example

#include <iostream>
using namespace std;
namespace abc
{
    int a=10;
}
namespace xyz
{
    int a=100;
}
int main()
{
    int a=1000;
    cout << "Hello world!" << endl;
    cout<<"a = "<<a<<endl; //1000
    cout<<"a = "<<abc::a<<endl; //10
    cout<<"a = "<<xyz::a<<endl; //100
    return 0;
}
/* Output */
ello world!
a = 1000
a = 10
a = 100

Nested namespace

namespace abc
{
int a=10;
namespace xyz
{
int a=20;
}
}

Cout<<“a = “<<abc::a<<endl; // 10
Cout<<“a = “<<abc::xyz::a<<endl; // 20

/* Nested namespace */
#include <iostream>
using namespace std;
namespace abc
{
    int a=10;
  namespace xyz
  {
    int a=100;
  }
}
int main()
{
    int a=1000;
    cout << "Hello world!" << endl;
    cout<<"a = "<<a<<endl; //1000
    cout<<"a = "<<abc::a<<endl; //10
    cout<<"a = "<<abc::xyz::a<<endl; //100
    return 0;
}
/* Output */
Hello world!
a = 1000
a = 10
a = 100