what is the proper case of constant class member fields according to the google c++ style guide?

1.1k Views Asked by At

So... I think this leaves a bit of room for interpretation, and I wanted to know if anybody knows what the spirit of the standard is...

class A {
  const int size_;
public:
  A(int size) : size_(size) {}
};
  1. Is the trailing underscore a sign of "private"-ness or "class"-ness?
  2. Is the const field supposed to be "kSize" or "size_"?
  3. If it is moved to be public, should it be "size"?
1

There are 1 best solutions below

4
On BEST ANSWER

In your example:

class A {
    const int size_;

This member variable is not a "constant" for the purposes of the style guide. Its value cannot be changed after construction, but is different per instance. A "constant" inside a class would be constexpr or static const or enum. As it stands, it is not a constant so does not get a k prefix.

To answer your specific questions individually:

  1. The trailing underscore tells you it's a class member variable.
  2. size_ because it's not a "constant" in terms of the style guide.
  3. Making it public would violate the style guide, so this doesn't really have an answer.

Finally, note that const member variables inhibit the compiler-generated assignment operator, which is one reason you don't see them that often.