Link to home
Start Free TrialLog in
Avatar of maheshhatolkar
maheshhatolkar

asked on

about namespaces

what are the namespaces in c++? what is the importance of them? can we create user defined namespaces?
ASKER CERTIFIED SOLUTION
Avatar of nietod
nietod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nietod
nietod

In a function, you cannot have two local variables with the same name.  However two seperate functions may have variables that have the same name, like in

void f1()
{
   int X;
   double X; // Error.
}

there is an error because the same name is used twice but in

void f1()
{
   int X;
}

void f2()
{
   double X;
}

there is no error bacuase the two names are iin seperate function, i.e. seperate scopes.

continues
A namespace works the same way.  It is a scope in which you can define templates, classes, constants, enums and other symbolic names.  Those names must be unique within that namespace but may be used in other namespaces. like

namepace vehicles
{
    class plane
    {
    };
};

namespace geometry
{
    class plane
    {
   };
}

the two classes defined are distinct classes buth they both can have the same name because they are defined in seperate namespaces.
>> what is the importance of them?
They are used to prevent naming conflicts.  This is especially important when dealing with code libraries.  For example the STL library defines a class caled "string"  Well string is a VERY popular name.  If that name was not placed in a namespace it would conflict with the name "string" used in other circumstances.  But the name is placed in a namespace called "std"

Note to use a name that is defined in a namespace, you must preceed the name with the namespace name and a scope resolution operaotr ("::")  Like to use the STL string, you woudl specify "std::string".  Another option is to include the std::string name into the current namespace using

using std::string;

Then you don't have to specify the "std::" before "string"  Finally you could all the names defined in the std namespace into the current namespace using a single statement like

using namespace std;

>> can we create user defined namespaces?
Absolutely.
Avatar of maheshhatolkar

ASKER

Thanks neitod, i got really a good answer.