c++constantsimplicit-conversionmultiple-indirection

Invalid conversion from int** to const int**


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?


Solution

  • I was mistaken about the constness 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 ints], 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 ints and the pointers to ints 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.