Stats

51 Contributors: 2 Wednesday, October 19, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Const Correctness

Syntax

  • class ClassOne { public: bool non_modifying_member_function() const { /* ... */ } };
  • int ClassTwo::non_modifying_member_function() const { /* ... */ }
  • void ClassTwo::modifying_member_function() { /* ... */ }
  • char non_param_modding_func(const ClassOne& one, const ClassTwo* two) { /* ... */ }
  • float parameter_modifying_function(ClassTwo& one, ClassOne* two) { /* ... */ }
  • short ClassThree::non_modding_non_param_modding_f(const ClassOne&) const { /* ... */ }

Remarks

const correctness is a very useful troubleshooting tool, as it allows the programmer to quickly determine which functions might be inadvertently modifying code. It also prevents unintentional errors, such as the one shown in Const Correct Function Parameters, from compiling properly and going unnoticed.

It is much easier to design a class for const correctness, than it is to later add const correctness to a pre-existing class. If possible, design any class that can be const correct so that it is const correct, to save yourself and others the hassle of later modifying it.

Note that this can also be applied to volatile correctness if necessary, with the same rules as for const correctness, but this is used much less often.

Refrences :

ISO_CPP

Sell me on const correctness

C++ Tutorial

Related Examples