Conventions for accessor methods (getters and setters) in C++

From my perspective as sitting with 4 million lines of C++ code (and that’s just one project) from a maintenance perspective I would say:

  • It’s ok to not use getters/setters if members are immutable (i.e. const) or simple with no dependencies (like a point class with members X and Y).

  • If member is private only it’s also ok to skip getters/setters. I also count members of internal pimpl-classes as private if the .cpp unit is smallish.

  • If member is public or protected (protected is just as bad as public) and non-const, non-simple or has dependencies then use getters/setters.

As a maintenance guy my main reason for wanting to have getters/setters is because then I have a place to put break points / logging / something else.

I prefer the style of alternative 2. as that’s more searchable (a key component in writing maintainable code).

Leave a Comment