views:

72

answers:

1

The const modifier in C++ before star means that using this pointer the value pointed at cannot be changed, while the pointer itself can be made to point something else. In the below

void justloadme(const int **ptr)
{
    *ptr = new int[5];
}

int main()
{
    int *ptr = NULL;
    justloadme(&ptr);
}

justloadme function should not be allowed to edit the integer values (if any) pointed by the passed param, while it can edit the int* value (since the const is not after the first star), but still why do I get a compiler error in both GCC and VC++?

GCC: error: invalid conversion from int** to const int**

VC++: error C2664: 'justloadme' : cannot convert parameter 1 from 'int *' to 'const int *'. Conversion loses qualifiers

Why does it say that the conversion loses qualifiers? Isn't it gaining the const qualifier? Moreover, isn't it similar to strlen(const char*) where we pass a non-const char*

+3  A: 

As most times, the compiler is right and intuition wrong. The problem is that if that particular assignment was allowed you could break const-correctness in your program:

const int constant = 10;
int *modifier = 0;
const int ** const_breaker = &modifier; // [*] this is equivalent to your code

*const_breaker = & constant;   // no problem, const_breaker points to
                               // pointer to a constant integer, but...
                               // we are actually doing: modifer = &constant!!!
*modifier = 5;                 // ouch!! we are modifying a constant!!!

The line marked with [*] is the culprit for that violation, and is disallowed for that particular reason. The language allows adding const to the last level but not the first:

int * const * correct = &modifier; // ok, this does not break correctness of the code
David Rodríguez - dribeas
Although it is agreeable that to disallow this `const` modifying fiasco the compiler does this. But using `int * const * correct` won't even allow me to do `*ptr = new int[5];`. What do I do?
legends2k
The problem is most probably in that what you want to do is not what you are writting. What is it that you want to be done? The signature takes a `const int **` but you are passing an `int **` and treating it inside the function as a `int **`... do you really want that `const` in the signature?
David Rodríguez - dribeas
Oh, now I get it! What I'm trying to do is conceptually wrong, so yes, you're right. Thanks!
legends2k