How it works...

Declaring objects and member functions constant has several important benefits:

  • You prevent both accidental and intentional changes of the object which, in some cases, can result in incorrect program behavior.
  • You enable the compiler to perform better optimizations.
  • You document the semantics of the code for other users.
Constant correctness is not a matter of personal style but a core principle that should guide C++ development.

Unfortunately, the importance of constant correctness has not been, and is still not, stressed enough in books, C++ communities, and working environments. But the rule of thumb is that everything that is not supposed to change should be declared constant. This should be done all the time and not ...

Get Modern C++ Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.