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.
Printable View
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.
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::)Code: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!
I think namespaces can be considered as packages which contains a number of classess variables etc.
Take a look at the reply of Andreas Masur in this thread
[ Merged threads ]