I will assume you meant to ask "Why?" or "What does it mean?"
Keep in mind that you can declare a variable as constant in two ways:
1 2
constint x = 0;
intconst y = 0;
I personally prefer the second form, because it is consistent with the use on member functions as you discovered. However, the first form is heavily used.
When you see const after a member function argument list, that means the member function cannot change the state of the object it is being invoked on - the compiler will enforce it by refusing to compile code that breaks this promise.
1 2 3 4 5 6 7 8 9 10 11 12
struct Example
{
int x;
void f()
{
x = 0; //fine
}
void g() const
{
x = 0; //error
}
};
void g() const When you create member function, aside from arguments you provided, there is another hidden argument: pointer to the object you are working with. That trailing const (and/or volatile or ref-qualifier &/&&) relates to that hidden argument. Compare: