pointer to pointer to const

M

Morten Frederiksen

Can anyone explain why this does not work?

int a = 42;
int* b = &a;
const int** c = &b; // error

I get "invalid conversion from `int**' to `const int**'" from the
compiler. Logically there should not be a problem, so perhaps it is a
limitation on the compiler.

Regards
Morten Frederiksen
 
M

Max M.

Morten said:
int a = 42;
int* b = &a;
const int** c = &b; // error

I get "invalid conversion from `int**' to `const int**'" from the
compiler. Logically there should not be a problem, so perhaps it is a
limitation on the compiler.

Logically there *is* indeed a problem. If that assignament were possibile,
you could change the content of 'b' by assigning a value to '*c'. Since
'*c' is of type 'const int*', 'b' could end up pointing to a 'const int'.

Max
 
P

Peter Julian

Morten Frederiksen said:
Can anyone explain why this does not work?

int a = 42;
int* b = &a;
const int** c = &b; // error

I get "invalid conversion from `int**' to `const int**'" from the
compiler. Logically there should not be a problem, so perhaps it is a
limitation on the compiler.

Regards
Morten Frederiksen

The compiler behaves as expected.

Because the constant keyword used above implies a constant value, not a
constant pointer. Since variable a is mutable, the pointer to a constant
can't bind to it.

Note:

#include <iostream>

int main()
{
const int aa = 11;
const int bb = 22;
const int *p_a = &aa;
const int *p_b = &bb;
const int **pp_c = &p_b;
*pp_c = p_a; // ok !, mutable pointer
// **pp_c = 23; // error... const object
std::cout << "**pp_c = " << **pp_c;

return 0;
}

and...

#include <iostream>

int main()
{
int aa = 11;
int bb = 22;
int *p_a = &aa;
int *p_b = &bb;
int * const * const pp_c = &p_a;
// **pp_c = &p_a; // error... const ptr to a const ptr
// *pp_c = p_b; // error... const ptr
**pp_c = 12; // ok !, mutable object
std::cout << "**pp_c = " << **pp_c;

return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,204
Messages
2,571,064
Members
47,672
Latest member
svaraho

Latest Threads

Top