Home > Articles > Programming > C/C++

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Why Use Namespaces?

The code we added in Listings 1 and 2 might seem overly complex, so why bother with namespaces at all? Well, one reason for using them that I hinted at above is the ability to hide information. Maybe you don’t want all your code to be visible to the users of your namespace? Let’s say we have another symbol in EventHandler.h that we need and it’s called SpecialEvent, as shown in Listing 3.

Listing 3 Another Symbol in The Header File

   EventHandler* _successor;
   Event _event;

typedef int SpecialEvent;

If we want to gain access to this symbol in EventHandler.cpp, we can use the code in Listing 4—note that I commented out the line using namespace eventHandling.

Listing 4 Namespace Using Declaration

//using namespace eventHandling;
using eventHandling::EventHandler;
using eventHandling::SpecialEvent;
const SpecialEvent LINK_2_BROKEN = 2;

Listing 4 shows how to use specific symbols in the eventHandling namespace (in this case, eventHandling::EventHandler and eventHandling::SpecialEvent). By doing this, we’re dipping into the namespace and pulling out only those symbols we want. This makes any other elements in the namespace invisible to the calling code. By making such symbols invisible, we make the calling code simpler and more modular.

We can also use namespaces for other reasons; for example, to solve the problem of symbol name conflicts.

  • + Share This
  • 🔖 Save To Your Account