Click to See Complete Forum and Search --> : about namespace


siya_pandya
March 19th, 2005, 01:06 AM
hi
i am learning c++.
i don't have any idea about namespace.
i am a begineer.
can anybody tell me what is namespace in c++ with small example.

chi_luci
March 19th, 2005, 01:32 AM
shortly, a namespace is an area where names (variables, functions, objects...) are visible. For namespaces it's just a matter of visibility. I'll give you an example:
int i; -> the i variable is visible global meaning it belongs to global namespace
namespace ns
{
int i;
}->in this case i is visible only is used in ns namespace meaning that you must use ns::i to reference it
a namespace is veri much like a class but very different
the differences between a class and a namespace:
- a class is an object, a namespace is just a way to group variables, functions, objects...
- a class has a c-tor and a d-tor, namespaces are not objects so they don't have any
- for a class you can define operators, for namespaces not

The advantages of using namespaces:
-sorting objects (classes, data types, variables ) to categories
-avoiding double declaring variables with same name..
....others......

eg:
namespace ns1
{
int i;
double f;
void func();
void f1();
}
namespace ns2
{
int i;
double f1;
void func();
void f();
}
void main()
{
ns1::i = 0;
ns2::i = 2;
ns1::func();
ns2::func();
printf( "%d, %d", ns1::i, ns2::i );
}
I don't know if it helped but I do hope so!
:)

Vinod S
March 19th, 2005, 01:59 AM
I think namespaces can be considered as packages which contains a number of classess variables etc.

Ejaz
March 19th, 2005, 02:02 AM
Take a look at the reply of Andreas Masur in this thread (http://www.codeguru.com/forum/showthread.php?t=312503)

Andreas Masur
March 19th, 2005, 04:50 AM
[ Merged threads ]