Code Organization with Namespaces
by Michael V. De Palatis


Namespaces are arguably one of the least-used tool by programmers. This is most unfortunate, though, since they can serve as a wonderful method of organizing code.

Anyone who has seen the line "using namespace std;" in a C++ introductory text probably has at least a slight idea as to what namespaces are. You should know, at least, that by using that line in your code, instead of typing "std::cout" or "std::endl", you can type simply "cout" and "endl". But what exactly is a namespace? Simply put, a namespace is a C++ tool for grouping functions, objects, and variables with a similar purpose together. This makes them superb for use in game development.

The general way to create namespaces is like this:

namespace utility
  void seedRandom();
  void seedRandom(unsigned int _seed);

Source File
namespace utility
  // seed random numbers based on the current time
  void seedRandom()
    time_t seconds;
    srand((unsigned int)seconds);

  // seed random numbers based on given value
  void seedRandom(unsigned int _seed)

(Alternatively, in the definitions, you could forgo the namespace utility and accompanying curly braces and instead type utility:: before every function name like you would with classes. However, the disadvantage to this is that you'd have to type utility:: before all variable names that are part of the utility namespace in addition to the function names.)

That is really all there is to it. After creating the namespace, you would include the header with the namespace declarations into any source file that needed it, and it's usable. Just like the old "using namespace std;", you can do the same thing with your own namespaces to avoid having to type the scope identifier each time. However, if you do this, be careful. Another reason for namespaces is to allow to avoid name collisions when functions and variables from two libraries get included in a single project. So, for example, if you had two namespaces, each with a variable named x, you would want to stay away from "using namespace blah;".

So, in review, namespaces allow modularization of code to easily take shape. With namespaces, you can easily separate the components of your engine (e.g., namespaces for the sound component, the display component, etc.) and further modularize already object-oriented code.

Sample code using namespaces can be found here.

Discuss this article in the forums

Date this article was posted to 12/14/2003
(Note that this date does not necessarily correspond to the date the article was written)

See Also:
Sweet Snippets

© 1999-2011 All rights reserved. Terms of Use Privacy Policy
Comments? Questions? Feedback? Click here!