In C++ sometimes I see declarations like below:
return_type function_name( datatype parameter1, datatype parameter2 ) const
{ /*................*/}
What does this const type qualifier exact do in this case?
In C++ sometimes I see declarations like below:
return_type function_name( datatype parameter1, datatype parameter2 ) const
{ /*................*/}
What does this const type qualifier exact do in this case?
The const qualifier at the end of a member function declaration indicates that the function can be called on objects which are themselves const. const member functions promise not to change the state of any non-mutable data members.
const member functions can also, of course, be called on non-const objects (and still make the same promise).
Member functions can be overloaded on const-ness as well. For example:
$9.3.1/3 states-
"A nonstatic member function may be declared const, volatile, or const volatile. These cvqualifiers affect the type of the this pointer (9.3.2). They also affect the function type (8.3.5) of the member function; a member function declared const is a const member function, a member function declared volatile is a volatile member function and a member function declared const volatile is a const volatile member function."
So here is the summary:
a) A const qualifier can be used only for class non static member functions
b) cv qualification for function participate in overloading
It means that it doesn't modify the object, so you can call that method with a const object.
i.e.
Means that if you have
you can call
without a compile error, because the method declaration indicates it doesn't change the object's data.