Const Correctness – C++ Tutorials – Cprogramming.com
The effects of declaring a variable to be const propagate throughout the program. Once you have a const object, it cannot be assigned to a non-const reference or use functions that are known to be capable of changing the state of the object. This is necessary to enforce the const-ness of the object, but it means you need a way to state that a function should not make changes to an object. In non-object-oriented code, this is as easy as using const references as demonstrated above.
In C++, however, there’s the issue of classes with methods. If you have a const object, you don’t want to call methods that can change the object, so you need a way of letting the compiler know which methods can be safely called. These methods are called “const functions”, and are the only functions that can be called on a const object. Note, by the way, that only member methods make sense as const methods. Remember that in C++, every method of an object receives an implicit this pointer to the object; const methods effectively receive a const this pointer.
The way to declare that a function is safe for const objects is simply to mark it as const; the syntax for const functions is a little bit peculiar because there’s only one place where you can really put the const: at the end of the function:
Footer: Autoposted dengan [ email ] dari [ sunu’s posterous ]