Invalid conversion from int** to const int**

2.6k Views Asked by At

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?

2

There are 2 best solutions below

8
On BEST ANSWER

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.

9
On

Greyson is correct that you'll want to use const int* const*, but didn't explain why your original version failed.

Here is a demonstration of why int** is incompatible with const int**:

const int ci = 0;
const int* pci = &ci;
int* pi;
int** ppi = π
const int** ppci = ppi; // this line is the lynchpin
*ppci = pci;
*pi = 1; // modifies ci!