When to use nested classes and when to use namespaces

c++11classnamespace

I have really never made use of namespaces, and am considering them at the moment.

My situation. I have a class Reverb. It contains as members instances of other classes, declared in the same header file, above it. Now there are appearing more and more data structures, relevant to the Reverb class e.g. 3 different representations of the user settings.

So I made a class Settings, that contains 3 sub-classes for the 3 representations and some methods to convert between them.

My question is where to place that?

  • Put it inside Reverb? Then the Reverb API becomes quite bloated and scroll-heavy.
  • Put it in file scope? Any user of the header will be unpleasantly surprised to find a class Settings, that actually means ReverbSettings.
  • Create a namespace Reverb and put everything in it? Then what to do with the class Reverb? It would be strange to ask for Reverb::Reverb.
  • Any better solution?

Best Answer

The questions to ask are can a nested class exist without its enclosing class? Does a nested class need intimate visibility into its enclosing class?

I tend to avoid nested classes in general because of the tight coupling. I would rather refactor the nested class to its own top-level class and use interfaces/pure virtual base classes to give it a reference to what used to be its enclosing class. Often what I find is I can have smaller classes that are more laser-focused on a single task and are reusable.

In C++ you also have the friend keyword which can provide visibility into class internals. While it should be used sparingly, it is useful for those cases where two classes need to work closely together but do not represent quite the same abstraction.

Short version: there is nothing wrong with nesting classes, but prefer namespaces. In rare cases where it is warranted, friend can also be used.