Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   confusion involving pointer to pointer when converting from derived to base (http://www.velocityreviews.com/forums/t459405-confusion-involving-pointer-to-pointer-when-converting-from-derived-to-base.html)

Kavya 12-23-2006 07:29 AM

confusion involving pointer to pointer when converting from derived to base
 
Since Circle is-a Shape we are allowed to do this

Circle *c = new Circle;
Shape *s = c; //Works

But we can't do this

Circle **cc = &c;
Shape **ss = cc; //Does not works

Similarly, we can convert a pointer to non-const to a pointer to const
but we may not convert a pointer to pointer to non-const to a pointer
to pointer to const:

char *s1 = 0;
const char *s2 = s1; // works.
char *a[MAX];
const char **ps = a; // Does not works

Can someone explain this?


Gianni Mariani 12-23-2006 08:43 AM

Re: confusion involving pointer to pointer when converting from derivedto base
 
Kavya wrote:
> Since Circle is-a Shape we are allowed to do this
>
> Circle *c = new Circle;
> Shape *s = c; //Works
>
> But we can't do this
>
> Circle **cc = &c;
> Shape **ss = cc; //Does not works


If this were to work, you would be able to do this:

Circle *c = new Circle;
Tri *t = new Tri;

Circle **cc = &c;
Shape **ss = cc;
* ss = t;

c.radius = 22; // OOOPS - undefined behaviour

which is not very desirable.

>
> Similarly, we can convert a pointer to non-const to a pointer to const
> but we may not convert a pointer to pointer to non-const to a pointer
> to pointer to const:
>
> char *s1 = 0;
> const char *s2 = s1; // works.
> char *a[MAX];
> const char **ps = a; // Does not works
>
> Can someone explain this?


Same thing.

char *s1 = 0;
const char foo[] = "FOO";
const char **ps = &s1; // is not allowed
*ps = foo; // s1 now points to foo
s1[0]='B'; // assigning a const char - not good.



BobR 12-23-2006 07:31 PM

Re: confusion involving pointer to pointer when converting from derived to base
 

Kavya wrote in message...
>Since Circle is-a Shape we are allowed to do this
>
>Circle *c = new Circle;
>Shape *s = c; //Works
>
>But we can't do this
>
>Circle **cc = &c;
>Shape **ss = cc; //Does not works
>
>Similarly, we can convert a pointer to non-const to a pointer to const
>but we may not convert a pointer to pointer to non-const to a pointer
>to pointer to const:
>
>char *s1 = 0;
>const char *s2 = s1; // works.
>char *a[MAX];
>const char **ps = a; // Does not works
>
>Can someone explain this?


Yep!

Alf P. Steinbach's "Pointers" document:
http://home.no.net/dubjai/win32cpptu...ters/ch_01.pdf

Read that, then come back if you need more help.

--
Bob R
POVrookie




All times are GMT. The time now is 10:23 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.