| johnhoffman (25) | ||||
If I add a const before a function parameter, that means I will not change the parameter within the function:
Furthermore, if I add a const at the end of a function signature, then I will not change any variables in the function:
Hence, is the const before the parameter redundant in this case since the const after the function signature already guarantees that I will change no variables in the function?
| ||||
|
|
||||
| iHutch105 (1080) | |
In point two, you can't add const at the end of a nonmember function.Adding it to the end of a member function guarantees that non of the member variables in the in the class will be modified. | |
|
Last edited on
|
|
| L B (3807) | |||
| |||
|
|
|||
| Framework (3237) | |||||
|
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:
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:
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 | |||||
|
Last edited on
|
|||||