After reading this, it is my understanding that declaring a method as const
prevents it from accidentally modifying the class's member variables.
const
methods commonly used?Declaring a member function with the const keyword specifies that the function is a "read-only" function that doesn't modify the object for which it's called. A constant member function can't modify any non-static data members or call any member functions that aren't constant.
Explanation: The constant member functions are a special type of member functions. These are intended to restrict any modification in to the values of object which is used to invoke that function. This is done to ensure that there are no accidental modifications to the object. 2.
Member functions are operators and functions that are declared as members of a class. Member functions do not include operators and functions declared with the friend specifier. These are called friends of a class. You can declare a member function as static ; this is called a static member function.
The Java equivalent of const In a language such as C++, the const keyword can be used to force a variable or pointer to be read-only or immutable. This prevents it from being updated unintentially and can have advantages when it comes to thread-safety.
Yes, const
should always be used, when appropriate.
It lets your compiler check your application logic, statically asserting const-correctness for free!
Some people even say that const
should be the default, and you should be forced to use mutable
for what is non-constant.
I use const extensively to communicate design intent. If I intended that a method was a pure query, and not a modification function, I would both enforce that and communicate it with a 'const' in the signature.
I encourage you to look at Meyer's thoughts on the matter of side-effect-free functions, and the implications that has on enabling testing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With