It is a way to let the compiler know that you do not change the object's data. This lets the compiler do fancy optimizations, and lets you use the object in places that it otherwise could not be or wouldn't be allowed to be.
In other words, it is your way of saying "I guarantee I will not change the object's state with this function."
struct point
{
double x, y;
// Getting the angle from the +X axis does not need to
// change the object -- this is a constant function.
double angle() const
{
return atan2( y, x );
}
// Setting the angle -- that requires a change
// to the data, so this function is not const.
void angle( double theta )
{
double s = sin( theta );
double c = cos( theta );
double xx = x*c - y*s;
double yy = x*s + y*c;
x = xx;
y = yy;
}
};
The this pointer is always assumed to be const, whether the function is or not. There isn't ever a valid reason to change it to point to something else.
bool same_isbn(const Sales_item &rhs) const;
without the const: bool same_isbn(const Sales_item &rhs);
would be equivalent to: bool same_isbn(Sales_item*constthis, const Sales_item& rhs);
It doesn't make a constant member function. It creates a member function that treats the member variables of the class as constant.
Just being more specific.
1 2 3
void calc_somthing() const; //can not change member variables
void calc_somthing(); //can change member variables
When we talk about pointers, you need to remember that there is a difference between the pointer, and the data that they store. The pointer is constant, but the data it stores may not be.
for example:
1 2 3
char* const ch(newchar('a'));
*ch = 'b'; //this is legal, because I'm not changing the pointer, just the data it stores.