C++ const Correctness
As a general principle of class design, encapsulation is good. It reduces the complexity of your code and reduces the number of possible interactions between classes. Using const member functions increases encapsulation by restricting the ways in which an object can be used in certain circumstances, particularly when objects are passed by constant reference to functions or member functions. The const modifier is evaluated at compile-time, so it costs nothing at run-time.
You now have the tools required to make your classes const correct. A proper const interface allows the compiler to do a lot of type-checking work for you in situations where constant objects are used. Without a const interface, the speed and encapsulation benefits of constant user-defined types is lost. A class designed without const member functions hamstrings those who would use the class, as there otherwise would be no way to use the class when objects of its type are passed by const references. As shown above, users of your classes have good reason to manipulate them in this way. Being const correct then comes full-circle, as only the const interface to your class is available in these situations.
Many programming practices and conventions are available that can improve code in all types of ways. The notion of const, though, is supported directly by the language and provides a free compile-time mechanism to better encapsulate the concepts within your programs as classes. The most fundamental unit of design in C++ is the class. Concise, simple and const correct class interfaces improve portability, add flexibility and provide a foundation for extending your design to previously unforeseen purposes.
The public interfaces of your classes are the ones used by developers, including yourself. Interfaces that exploit the value of const modifiers promote looser coupling between classes by further limiting the public interface. Looser coupling provides a better foundation for expanding and re-tooling your classes for future situations. Designing for future changes is essential, and const correctness is an important principle to follow in future-proofing your class designs today.
Dave Berton is a professional programmer. He can be reached at firstname.lastname@example.org.
- One Port to Rule Them All!
- Privacy Is Personal
- PHP for Non-Developers
- Secure Server Deployments in Hostile Territory
- Linux Kernel 4.1 Released
- Django Templates
- July 2015 Issue of Linux Journal: Mobile
- A Code Boot Camp for Underprivileged Kids
- Practical Books for the Most Technical People on the Planet
- Attack of the Drones