const conersions

R

Rahul

Hi,
Why does the following gives a compilation error

int const * * p1= 0;
int * * p2 = 0;
p1 = p2;

p1 has more const restriction than p2 so increasing const'ness should
always be allowed, there's no harm which p1 could do to the value
pointed to by p2. So why is this an error.

Regards
 
J

joseph cook

Hi,
Why does the following gives a compilation error

int  const *  *  p1= 0;
int   *  *  p2 = 0;
p1 = p2;

p1 has more const restriction than p2 so increasing const'ness should
always be allowed, there's no harm which p1 could do to the value
pointed to by p2. So why is this an error.

Regards

You aren't really increasing or decreasing "const'ness". p1 is a
pointer to type A, and p2 is a pointer to type B. (Where A is a
pointer to a const int, and B is a pointer to int). In a way,
neither p1 or p2 have any const qualifiers at all (both are non
const).

Interestingly, if you change you first line to:

int const * const * p1 = 0;

and it compiles fine.
 
J

Juha Nieminen

joseph said:
You aren't really increasing or decreasing "const'ness". p1 is a
pointer to type A, and p2 is a pointer to type B. (Where A is a
pointer to a const int, and B is a pointer to int).

Why can't you assign a "pointer to int" to a "pointer to const int"?
It doesn't sound like this assignment would lose any qualifiers.
 
J

James Kanze

Why does the following gives a compilation error
int const * * p1= 0;
int * * p2 = 0;
p1 = p2;

Because it's illegal. It breaks const-ness without a cast.
p1 has more const restriction than p2 so increasing const'ness
should always be allowed, there's no harm which p1 could do to
the value pointed to by p2. So why is this an error.

int const i = 42 ;
int * pi ;
int ** p1 = &pi ;
int const** p2 = p1 ;
*p2 = &i ;
*pi = 0 ;

What does pi point to? The converions of &pi to an int const**
allows making it point to a const object, without a const_cast.
In other words, it breaks const.
 
J

James Kanze

Why can't you assign a "pointer to int" to a "pointer to const
int"? It doesn't sound like this assignment would lose any
qualifiers.

You can, but that's not what he's attempting to do. What he's
trying to do breaks const-ness; see my other posting.
 

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

No members online now.

Forum statistics

Threads
474,169
Messages
2,570,919
Members
47,460
Latest member
eibafima

Latest Threads

Top