|
| 1 | +# Be clear what kind of class you're writing. |
| 2 | + |
| 3 | +Just as there are design patterns for object-oriented programming, so there are patterns in the classes we usually write. Item 32 advises to know of these usual kinds of classes, and describes the following taxonomy: |
| 4 | + |
| 5 | +## Value Classes |
| 6 | + |
| 7 | +*Value classes* the most common tool in our class-toolshed. They are the basic, no-magic workhorse and identified by the following characteristics: |
| 8 | + |
| 9 | +* They have a public destructor, copy constructor and assignment operator, |
| 10 | +* They have no virtual functions, |
| 11 | +* They are intended to be used as concrete classes and not as base classes, |
| 12 | +* They are usually instantiated on the stack or held in another class. |
| 13 | + |
| 14 | +## Base Classes |
| 15 | + |
| 16 | +Base classes are any classes that are used as "internal nodes" in our inheritance hierarchy, i.e. any class that one or more other classes derive from. They share the following properties: |
| 17 | + |
| 18 | +* They have a virtual destructor, |
| 19 | +* They establish an interface through virtual functions, |
| 20 | +* They are usually instantiated on the heap. |
| 21 | + |
| 22 | +We could split this up into two further variants of this type of class: |
| 23 | + |
| 24 | +1. An *abstract class* is intended to be used in the context of polymorphism, i.e. pointers of their type will point to base classes, |
| 25 | +2. A *base class* is a class that refactors common functionality of its subclasses to avoid code duplication, but is not intended to be used for polymorphism. |
| 26 | + |
| 27 | +Note that both should be implemented in the usual ways (with virtual methods). The distinction is more in nomenclature and use. |
| 28 | + |
| 29 | +## Trait Classes |
| 30 | + |
| 31 | +A trait class is a template class that carries information about types. It is useful in the context of template metaprogramming. Such classes usually: |
| 32 | + |
| 33 | +* Contain only `typedef`s (aliases) and static functions, but do not carry state, |
| 34 | +* Are never instantiated (this can be enforced by `delete`ing constructors). |
| 35 | + |
| 36 | +## Exception Classes |
| 37 | + |
| 38 | +Exception classes are interesting in that they usually have both *value and reference* semantics: they are thrown by value but caught by reference. An exception class: |
| 39 | + |
| 40 | +* Has a public destructor and noexcept (copy) constructors. Otherwise you risk an abortion. |
| 41 | +* May have virtual functions. |
| 42 | +* Should derive from `std::exception` (or a subclass thereof). |
0 commit comments