1

Consider the following code:

int** a;
const int** b;
b = a;

This code gives an error:

error C2440: '=' : cannot convert from 'int **' to 'const int **'
Conversion loses qualifiers

Why i am not able to perform the cast?

When operating simple pointers it works ok.

int* a;
const int* b;
b = a;
lightstep
  • 765
  • 2
  • 8
  • 19

1 Answers1

3

Suppose you were able to perform this cast. Consider:

const int n = 42;
const int* cp = &n;

int* p;
int** a = &p;

const int** b;
b = a;  // hypothetical, doesn't compile
*b = cp;  // equivalent to p = cp;
*p = 84;  // equivalent to n = 84: oops

Therefore, allowing an implicit cast from int** to const int** would allow a program to violate const correctness.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85