Consider a situation, when we have two persons with the same name, Deepak, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area if they live in different area or their mother or father name, etc.
Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.
A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. Using namespace, you can define the context in which names are defined. In essence, a namespace defines a scope.
//Example
for data only here…you can perform on function with same name in similar way.
#include
<iostream>
#include
<conio>
#include
<stdio>
namespace
Deep1
{
int
a=10;
float
b=2.3;
}
namespace
Deep2
{
int
a=5;
float
b=3.8;
}
namespace
Deep3
{
int
a=-4;
float
b=-6.8;
}
void
main()
{
using
namespace Deep1; //for whole Deep1
namespace
printf("a=%d",a);
printf("\nb=%f",b);
using
Deep2::b; //for only selected
members of the Deep2 namespace
cout<<"\nb="<<b;
cout<<"\na="<<Deep3::a; //using scope resolution operator
cout<<endl<<"b="<<Deep3::b;
getch();
}
No comments:
Post a Comment