Have You Thought About Using a Namespace in C++?

As someone originally coming from Python and then learning C++ later, namespaces were a new concept to me.  For the longest time, I was interacting with the ones in the standard library, but not really writing my own. However, at one point I was working on a personal project (an emulator if you are interested!) and realized I had a ton of functions that were all related, but I couldn’t figure out a good way to organize them together.  A class felt like too much, but at the same time having them be standalone functions wouldn’t work.  I needed some other way to group them together.

This is where namespaces come in.  A namespace is a way that you can group functions together under a single name.  It’s very simple to do:

C++
namespace foo
{
  void find();
}

Then you can simply use your functions like this:

C++
foo::find();

Compared to classes, namespaces offer a simpler set of functionality.  Classes are great if you want the ability to create objects that have internal data and methods, and you want those methods to be able to act on the data.  On the other hand, a namespace is quite a bit more simple.  It’s just a wrapper around a collection of variables and methods.  Not only does it keep your code more organized, but it also helps to prevent name overlap.

In C++ if you have two functions with the same name, you’ll get an error on compile letting you know the name is already used somewhere.  For instance, maybe you are using the std::find function from the STL, but then you want to make your own find function.  By wrapping your function in a namespace you can prevent this from happening. Then you simply use your function by calling my_namespace::find instead.

My point here is not that you should always use namespaces.  What I want to point out is that you should always consider what functionality your code needs.  When you use a class, you are opening up the possibility to have member variables, private functions and public functions.  In some cases though, you may not need or want that possibility to be there.  If you need it, then absolutely use a class, but if not, a namespace might be just what you need.

If you want to read more about namespaces, please checkout the link below.

References for Namespaces

Microsoft Reference for Namespaces

CppReference on Namespaces


Posted

in

, ,

by

Comments

Leave a Reply

en_USEN