Namespacce Scope
Chapter 16
1
Introduction
Define variables in different scopes in C++
(e.g classes, fuctions).
C++ add “namespace” to define a scope
that could hold global identifiers.
All classes, functions and templates are
declared within namespace “std”.
“using namespace” specifies that the
members defined in “std” namespace will be
frequently throughout the program.
2
Defining a Namespace
General form of namespace is:
namespace namespace_name
{
//Declaration of
//variables, functions, classes,
etc.
}
3
Build your NameSpace
Variable m and function display are inside the
scope defined by TestSpace.
IF you want to assign a value to m, you must
use scope resolution like TestSpace :: m
=100; namespace TestSpace
{
int m;
void display(int n)
NameSpace Declare: {
cout<<n;
}
} //No semicolon here
4
“using” directive
Scope resolution becomes cumbersome if
members of a namespace are frequently used.
So, we can use a “using” directive.
Using namespace namespace_name; //using
directive
Using namespace_name:: member_name; //using
declaration
First, All the members declared within the
specified namespace may be accessed without
using qualification.
Second, we can access only the specified member.
5
“using” directive
Using namespace TestSpace;
M= 100; //Ok
Display(200); //Ok
Using TestSpace:: m; //using declaration
M=100; // Ok
Display(200); //Not ok, display not visible
6
Nesting of NameSpace
nest namespaces within other namespaces to
create a hierarchical structure.
namespace OuterNamespace
{
//declarations for outer
namespace
namespace InnerNamespace
{
//declarations for outer
namespace
}
}
7
Nesting of NameSpace
Namespaces provide a scope for identifiers
(variables, functions, classes). By nesting
namespaces, you can prevent naming conflicts
between identifiers in different namespaces. For
example: namespace Math
{
int Add(int a, int b) { return a+b; }
namespace Physics
{
int Add(int a, int b) {return
a-b;}
}
}
8