const
is used either with a value or with a pointer.
In case of a value the story is simple: you put the
const
keyword in front of a function parameter declaration or a local/global variable that isn't a pointer or reference:
const int j = 5;
void func(const in x)
{
const float f = 0.5f;
}
I think the meaning of
const
in these cases is obvious.
Pointer/reference: I demonstrate just the pointers,
const
works the almost the same way for references (that are essentially pointers but you can/must initialize them exactly once when you declare them).
const int*
and
int const*
mean the same: The
int
value or
int
array referenced by the pointer is constant.
int* const
means that the pointer variable itself is constant but the data referenced isn't! You can of course combine these:
const int* const
.
Now a special case comes: const method:
class C
{
void Method(int param) const
{
}
};
This isn't really a special case. The const after the method is used with the hidden
this
pointer parameter of the method.
So if the "pseudo code" of a normal non-const method looks like this:
class C
{
void Method(C* const this, int param)
{
}
};
then the "pseudo code" of a
const
method is the following:
class C
{
void Method(const C* const this, int param)
{
}
};
You simply can't write const there in front of the hidden this pointer so the language forces you to write that const after the method "header" declaration.
The
this
pointer value itself is always
const
even in case of non-const methods, you cant change the value of "
this
". By making a method
const
you mark the instance referenced by the
this
pointer as
const
. The result is that you can not call non-const instance methods from that
const
method and you can not modify the member variables of the instance because you have only a
const C* const this
pointer...
Wise use??? If you don't want someone to modify a value or data referenced by a pointer then declare it as const. Period. If you know that a method doesn't have to modify any member variables and it doesn't have to call other non-const members then declare the method as const. Typical example:
class Array
{
public:
....
size_t GetLength() const
{
}
void Clear()
{
...
}
....
};
void Test(const Array& arr)
{
arr.GetLength();
arr.Clear();
}
EDIT: avoid the usage of the
mutable
keyword that is basically a hack. I've seen maybe one place where it's usage was reasonable.