What are the pros and cons of using nested public C++ classes and enumerations? For example, suppose you have a class called printer, and this class also stores information on output trays, you could have:
class printer { public: std::string name_; enum TYPE { TYPE_LOCAL, TYPE_NETWORK, }; class output_tray { ... }; ... }; printer prn; printer::TYPE type; printer::output_tray tray;
Alternatively:
class printer { public: std::string name_; ... }; enum PRINTER_TYPE { PRINTER_TYPE_LOCAL, PRINTER_TYPE_NETWORK, }; class output_tray { ... }; printer prn; PRINTER_TYPE type; output_tray tray;
I can see the benefits of nesting private enums/classes, but when it comes to public ones, the office is split – it seems to be more of a style choice.
So, which do you prefer and why?
Nested classes
There are several side effects to classes nested inside classes that I usually consider flaws (if not pure antipatterns).
Let’s imagine the following code :
Or even:
So:
As a conclusion, unless exceptions (e.g. the nested class is an intimate part of the nesting class… And even then…), I see no point in nested classes in normal code, as the flaws outweights by magnitudes the perceived advantages.
Furthermore, it smells as a clumsy attempt to simulate namespacing without using C++ namespaces.
On the pro-side, you isolate this code, and if private, make it unusable but from the "outside" class…
Nested enums
Pros: Everything.
Con: Nothing.
The fact is enum items will pollute the global scope:
Ony by putting each enum in a different namespace/class will enable you to avoid this collision:
Note that C++0x defined the class enum:
exactly for this kind of problems.