Re: just out of curiosity (Björn)

Björn Lindberg d95-bli at nada.kth.se
Thu Aug 12 04:05:00 PDT 2004


michael <michael8110 at terra.com.br> writes:

> Björn,thanks for the indication of the tutorial,i'll be studying it
> after  my head has had a chance to cool off-right now i'm feeding it
> only the  likes of ella fitzgerald,billie holiday,louis armstrong
> :-);one last  thing,though-any special reason why would you prefer to
> pepper your code  with all those std:: when you can start off with "
> using namespace std;" ?

When writing larger programs, you typically use code which reside in
several different namespaces. If you were to import them all, there is
a high risk of name collisions. A using directive imports /all/ the
names into your namespace, and you cannot really know which they
are. A solution is to only import selected names, but it quickly
becomes tedious to keep the import lists in sync with the rest of the
code. I prefer explicitly giving the namespace prefix, which also in a
larger program helps to show where a name came from.

The risk of collisions is larger than one might think, because when
using namespaces, people will in general (and rightly so) choose
shorter names for their functions and types. Compare with C, which
doesn't have namespaces[*]. A typical C library uses prefixes to all
their names as sort of a poor man's namespace. In the GTK library for
instance, all object names are of the form GtkButton, GtkToggleButton,
GtkCheckButton, etc. In contrast, the standard library of C++ has
functions with names such as `find', `equal', `copy', etc. Ie, short
and general names which could definitely exist in other libraries as
well.

Another thing to note is that you can have namespace aliases. A
namespace alias is a new name for an existing namespace. For instance,
you can make a short name an alias for a long, or even nested,
namespace name:

namespace vehicles
{
    namespace earth_bound
    {
	class car
	{
	public:
	    std::string itsName;
	};
    }
}

namespace ebv = vehicles::earth_bound;

int main()
{
    ebv::car c; // Equivalent to vehicles::earth_bound::car
    // [...]

    return 0;
}

  [*] They may have incorporated it in recent standards, but for the
      overwhelming part of the liftime of C, it didn't exist.


Björn



More information about the lfs-chat mailing list