The easy way to remember it is to read delcarations "backwards", from right to left. Pronounce the * as "pointer to" and & as "reference to"
So
const type* argument would be read as "argument is a pointer to a const type".
Meaning the pointer itself is not const (argument = &foo is OK)
but the data it points to is const (*argument = foo is error)
Likewise
const type* const argument would be "argument is a const pointer to a const type".
Meaning the pointer itself is const (argument = &foo is error)
and so is the data it points to (*argument = foo is error)
const type& argument just means that argument is a reference to a const type. Therefore argument cannot be modified (argument = foo is an error)
| Furthermore it is my understanding that the use of const speaks to the compiler directly and does not generate run-time errors. |
Usually, yes. There are instances where some memory might actually be read-only and therefore is strictly const at runtime. However that isn't very often.
| Is using const another form of OO data protection that is the responsibility of the coder to integrate? |
It's kind of a code clarity thing. Passing things by const reference or const pointer tells you that the function will not modify the object you're passing.
1 2 3 4 5 6 7 8 9 10
|
void Foo(const Obj& v);
void Bar(Obj& v);
int main()
{
Obj o;
Foo(o); // I can rest easy knowing this will not modify o
Bar(o); // on the other hand, this likely will modify o
}
|