Use a conventional class member declaration order
Reason
A conventional order of members improves readability.
When declaring a class use the following order
- types: classes, enums, and aliases (
using) - constructors, assignments, destructor
- functions
- data
Use the public before protected before private order.
This is a recommendation for when you have no constraints or better ideas. This rule was added after many requests for guidance.
Example
class X {
public:
// interface
protected:
// unchecked function for use by derived class implementations
private:
// implementation details
};
Example
Sometimes, the default order of members conflicts with a desire to separate the public interface from implementation details. In such cases, private types and functions can be placed with private data.
class X {
public:
// interface
protected:
// unchecked function for use by derived class implementations
private:
// implementation details (types, functions, and data)
};
Example, bad
Avoid multiple blocks of declarations of one access (e.g., public) dispersed among blocks of declarations with different access (e.g. private).
class X { // bad
public:
void f();
public:
int g();
// ...
};
The use of macros to declare groups of members often leads to violation of any ordering rules. However, using macros obscures what is being expressed anyway.
Enforcement
Flag departures from the suggested order. There will be a lot of old code that doesn't follow this rule.