C++ Const Correctness

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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



Got any C++ Question?