I have a class with a 2D array of ints implemented as an int**. I implemented an accessor function to this 2D array as follows, returning a const int** to prevent the user from being able to edit it:
const int** Class::Access() const
{
return pp_array;
}
But I got the compilation error "invalid conversion from int** to const int**". Why is a promotion to const not allowed here? How can I give the user access to the information without editing rights?
I was mistaken about the
const
ness of the method being the reason for the error. As Ben points out, theconst
-ness of the method is irrelavent, since that applies only to the value of the exterior pointer [to pointers toint
s], which can be copied to a mutable version trivially.In order to protect the data (which is your preferred outcome) you should make both the
int
s and the pointers toint
s constant:Will work.
If you prefer to have the const in front you can also write the declaration like so:
but since the second
const
applies to the pointers, it must be placed to the right (like theconst
which applies to the method) of the asterisk.