Thursday, September 25, 2008

C++ Coding Standard: Class Layout

The previous section of the C++ coding standard dealt with important questions of class design. This section, dealing with how to lay out the class definition, is less important. But you should choose some organization for the declarations in a class, just for readability. Here's one way to do it.
  • 7.1. All public things first, then all protected, then all private.
  • 7.2. Within a public or private section, use the following order:
    • 7.2.1. First any nested type definitions or typedefs.
    • 7.2.2. Then constructors, destructors, and the assignment operator.
    • 7.2.3. Then any const member functions.
    • 7.2.4. Then any non-const member functions.
    • 7.2.5. Then any static member functions.
    • 7.2.6. Then any data members.
  • 7.3. Define inline functions outside of the class definition.
Although the default visibility for classes is private, most people agree that public information should go at the top, since that's the most interesting to a user of the class. Constructors are also of primary interest and should go near the top.

For a similar reason, I think inline definitions should be below the class definition. They are really an implementation detail that should not be of interest to a user of the class -- so put them at the bottom of the file. I do not agree with putting the inline definitions in a separate file. When you're trying to figure out what some function does, you usually start in the header file. If you need to look at the implementation, you might find it inline in the file you're already looking at; otherwise it's in the .cpp file. It's confusing to have a third file containing the inline functions -- just don't do that.

Next: inheritance.

No comments: