const
keyword
Three const
placement:
1.
Using const
member functions provides the following benefits:
- It enables the usage of the member function on
const
objects, allowing you to invoke the function without the risk of unintended modification of the object’s state. - It allows the compiler to enforce the immutability of the object within the function, preventing accidental modifications.
- It provides clarity to the code readers that the member function does not modify the object.
In the given example, the operator-
function is marked as const
because it performs a subtraction operation between two Rational
objects but does not modify the current object.