Explain: Converting 'char **' to 'const char **', Conversion loses qualifiers

c++, casting, constants

Solution

Yes, you cannot implicitly convert from a `T **` to a `const T **`, because the compiler can no longer guarantee that the const-ness won't be violated.

Consider the following code (borrowed from the C FAQ question on exactly this topic: Why can't I pass a `char **` to a function which expects a `const char **`?):

const char c = 'x';
char *p1;
const char **p2 = &p1;  // 3
*p2 = &c;
*p1 = 'X';              // 5

If the compiler allowed line 3, then line 5 would end up writing to a `const` object.

Problem

Possible Duplicate: Implicit cast from char** to const char** Given the following code: ``` void foo( const char ** buffer ); void bar() { char * buffer; foo( &buffer ); } ``` Why is it that if the `foo()` function has a `const char *` parameter the compiler doesn't complain when passing in a `char *` variable into it? But when using `char **`, it cannot convert it to `const char **`? Does the compiler add any `const` qualifiers in the former case? I've read section 4.4 of the C++ standard and it just confused me further.

Original source

Related problems