The "
const" in either context mean the same thing more or less.
If a parameter is a reference to a constant ("
const Dog &dog") it allows temporary instances [of "
Dog"] to be bound to it [the reference]. However, if the parameter becomes constant; its state can no longer change. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
void FunctionA( Class &InstanceA )
{
InstanceA.Member = ...;
}
void FunctionB( Class const &InstanceB )
{
InstanceB.Function( );
}
int main( )
{
FunctionA( ( Class( ) ) ); // Error: expected an l-value instance of "Class".
FunctionB( ( Class( ) ) ); // OK
Class Instance;
FunctionB( Instance ); // OK, but "Instance" cannot be modified by "FunctionB( )".
}
|
If a temporary "
Class" instance is passed to "
FunctionB( )", the temporary instance will have its lifetime match that of the "
InstanceB" parameter of "
FunctionB( )". In other words, when "
InstanceB" goes out of scope at the end of "
FunctionB( )" so will the temporary instance.
If a member-function is constant, it tells the compiler that the function will not alter the state of the instance pointed to by "
this"; the "
const" after a function's parameter list modifies the declaration of the "
this" parameter. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
// "this" is implicitly added by the compiler, but I've added it for clarity.
// Without the "const" qualifier:
void Class::Function( Class * const this, int Parameter )
{
// "this" is a constant pointer ["this" isn't allowed to be reseated] to a non-constant "Class".
}
// With the "const" qualifier:
void Class::Function( Class const * const this, int Parameter ) const
{
// "this" is a constant pointer to a constant "Class".
}
|
Note the difference in the two declarations of "
this". However, if a data-member is mutable, the function is permitted to modify the [mutable] data-member.
Wazzak