Re: What makes namespace a powerful tool?

[ Follow Ups ] [ Post Followup ] [ CS2704 Web Discussion Board ] [ FAQ ]

Posted by William D McQuain on December 07, 2001 at 12:31:00:

In Reply to: What makes namespace a powerful tool? posted by James Chung on December 06, 2001 at 23:53:54:

: I know we haven't really used namespace at all, but from what I've been reading, it seems to be a powerful tool when writing classes. Does anyone know about this in detail? I'm sure C++ Standard Committee decided to switch to using namespaces for good reasons.

The main advantage is when you're trying to integrate code from one or more libraries into your own project. For example, suppose I've written a library that has something like:

int perfectFn(const string& S);

and you want to use that part of my library (for which you will probably NOT have the source). No problem, you just include my header file to get the prototype and you're in business.

Except, there's another unrelated library from which you want to use a function, and unfortunately in that library the function you want also has the prototype

int perfectFn(const string& S);

Well, you can't have both those prototypes in the same scope, so you're in trouble. The same issue could arise with two class declarations in different libraries; basically you have a name clash.

Now, if the authors of both the libraries used the namespace construct, then you'd have two header files containing something like:

namespace McQuainsLibrary {

int perfectFn(const string& S);



namespace BarnettesLibrary {

int perfectFn(const string& S);


So, in your code, you could do this:

#include "McQuainsLibrary.h"
#include "BarnettesLibrary.h"

int McValue = McQuainsLibrary::perfectFn(foo);

int BarValue = BarnettesLibrary::perfectFn(foo);

and there's no confusion about which function should bind to each call.

Follow Ups:

Post a Followup




Optional Link URL:
Link Title:
Optional Image URL:

[ Follow Ups ] [ Post Followup ] [ CS2704 Web Discussion Board ] [ FAQ ]