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, the const
-ness of the method is irrelavent, since that applies only to the value of the exterior pointer [to pointers to int
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 to int
s constant:
int const * const * Class::Access() const
{
return pp_array;
}
Will work.
If you prefer to have the const in front you can also write the declaration like so:
const int * const * Class::Access() const;
but since the second const
applies to the pointers, it must be placed to the right (like the const
which applies to the method) of the asterisk.