Possible Duplicate:
What is the meaning of a const at end of a member function?
If my class definition is as follows:
type CLASS::FUNCTION(int, const char*) const
What does the last const after the closing bracket mean, and how do I apply it to the function:
type CLASS::FUNCTION(int var1, const char* var2) { }
The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided. A const member function can be called by any type of object.
A const object can be created by prefixing the const keyword to the object declaration. Any attempt to change the data member of const objects results in a compile-time error. When a function is declared as const, it can be called on any type of object, const object as well as non-const objects.
The rule is: const applies to the thing left of it. If there is nothing on the left then it applies to the thing right of it.
Class constants can be useful if you need to define some constant data within a class. A class constant is declared inside a class with the const keyword.
It means that this function does not modify the observable state of an object.
In compiler terms, it means that you cannot call a function on a const
object (or const reference or const pointer) unless that function is also declared to be const
. Also, methods which are declared const
are not allowed to call methods which are not.
Update: as Aasmund totally correctly adds, const
methods are allowed to change the value of members declared to be mutable
.
For example, it might make sense to have a read-only operation (e.g. int CalculateSomeValue() const
) which caches its results because it's expensive to call. In this case, you need to have a mutable
member to write the cached results to.
I apologize for the omission, I was trying to be fast and to the point. :)
const
at the end of the function means it isn't going to modify the state of the object it is called up on ( i.e., this
).
type CLASS::FUNCTION(int, const char*) const ; // Method Signature type CLASS::FUNCTION(int var1, const char* var2) const { }
You need to mention the keyword const
at the end of the method definition too. Also note that only member functions can have this non-modifier keyword const
at their end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With