pointer to pointer - const correctness

Hi,


I would like to know why the initialization of p2 is illegal (see code below), I have the given comments:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main()
{

    int v1 = 10; 

    int* p1 = &v1;

    const int** p2; 
    
    p2 = &p1; //why is this illegal ?
              //According to what I understand the const means, **p2 can't be modified
              //I am only trying to be more restrictive

    return(0);
}



I have explained what I have understood with an example:

 
const int * const * const p3 = &p1;


From the above statement, I have explained what each const means:
The first const means, **p3 = 10 is illegal
The second const means, *p3 = NULL is illegal
The third const means, p3 = NULL is illegal

Thanks,
Muthu
It's a type mismatch -- &v1 is int**; p2 is const int**. They are not the same.
Thanks jsmith for the reply, I have given below my views:

I agree the types are different, but that is not reason enough for it to be illegal, I suppose there must be a reason why a const int** can't be initialized with int**.

The following involves 2 different types but is legal.

 
const int * const * const p3 = &p1;


I would like to know the underlying concept as to why it is illegal.
The below mentioned was explained to me by someone a few min back, I thought it would be worth while to let you all know the same:

This is not a conversion that C++ allows implicitly, and for good reason, because it would allow **p2 to be modified implicitly. To see how, take a look at the following example:

1
2
3
4
5
const int v1 = 10; // this is a constant it should never change 
int* p1; 
const int** p2 = &p1; // in reality this is illegal 
*p2 = &v1; // this is allowed since both "*p2" and "&v1" have type "const int*" 
*p1 = 11; // now we have modified v1!!! 


More generally, C++ allows the implicit conversion of T* to const T*, because that cannot lead to a situation like the above where a constant value is modified.

 
int * const * p2 = &p1;


would be OK (in that case the line "*p2 = &v1;" would give an error because you're trying to modify a constant pointer)

Thanks all
Topic archived. No new replies allowed.