Home > Articles > Programming > C/C++

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

Like this article? We recommend

User-Defined Namespaces

Using the code from my previous article, "C++ Chain of Responsibility Pattern" (see the link at end of this article), Listing 1 illustrates the addition of a namespace called eventHandling to a header file EventHandler.h. Just add the first line in Listing 1 at the point where you want your namespace to begin and then surround the requisite code with braces. Hey presto! You have your first user-defined namespace! In this case, the namespace is called eventHandling, but you can choose any name you like (apart from reserved keywords!).

Listing 1 Creating Your First Namespace

namespace eventHandling
{
class EventHandler {
public:
   EventHandler(EventHandler* = 0, Event = No_Event_Support);
   virtual bool HasEventSupport();
   virtual void SetHandler(EventHandler*, Event);
   virtual void HandleEvent();
private:
   EventHandler* _successor;
   Event _event;
};
}

To test this, try building the corresponding C++ file EventHandler.cpp. You should see namespace-related errors relating to the EventHandler symbol because we effectively made the class EventHandler private. We can fix the problem by adding the second line in Listing 2 at the top of EventHandler.cpp.

Listing 2 Adding the new namespace contents to the current scope

using namespace std;
// Now, inject the new namespace contents to the current scope
using namespace eventHandling;
const Event LINK_1_BROKEN = 1;

Now when you recompile the project, the new namespace code should function properly. We can use such new namespaces anywhere in a compilation unit—not just at the beginning as in Listing 2.

  • + Share This
  • 🔖 Save To Your Account