Newsgroups: comp.lang.c++
Path: utzoo!utgpu!news-server.csri.toronto.edu!torsqnt!geac!alias!rae
From: rae@alias.com (Reid Ellis)
Subject: Re: Reference problem??
Message-ID: <1991Apr29.170148.28543@alias.com>
Sender: news@alias.com (USENET News)
Organization: Alias Research, Inc. Toronto ON Canada
References: <CIMSHOP!DAVIDM.91Apr24233547@uunet.UU.NET> <CIMSHOP!DAVIDM.91Apr25095910@uunet.UU.NET>
Distribution: comp
Date: Mon, 29 Apr 91 17:01:48 GMT

text in []'s omitted for brevity's sake.

David S. Masterson <cimshop!davidm@uunet.UU.NET> writes:
|class alpha { [..] };
|class beta : public alpha { [..] };
|class gamma : public beta { [..] };
|
|void testfunc(alpha*& parm) {
 [..]
|	parm = new alpha(40);
 [..]
|}
|
|int main() {
|	gamma	g(10, 20, 30);
 [..]
|	gamma	*gptr = &g;
 [..]
|	testfunc((alpha*) gptr);
|		// ^-- why is the cast necessary?
 [..]
|}
|
|I don't understand why the cast is necessary.

This has to do with the fact that when you cast from a derived class
to a base class, the value of the pointer can change.  This has been
the case since multiple inheritance came into being in C++ [and quite
possibly, since before then].  In the above program, when you cast
"gamma *gptr" to an "alpha*", the value of gptr may be changed to
point to its "alpha part".  This pointer is then passed in to
testfunc().  testfunc(), which takes a reference to said pointer can
now set it to point at anything that may or may not be a "gamma".  Now
in main() when you return from the call to testfunc(), C++ will have no
idea what to do with gptr.  Should it offset it back to where it was,
relative to the [new] value of its "alpha" pointer?

Basically, you're trying to rip out the guts of a gamma. :)  As long
as a gamma* has the same pointer value as its respective alpha*, your
cast will work.  But if, say you were to do something like this:

	class beta : public something, public alpha { .. };

then your cast would no longer be valid..

						Reid
--
Reid Ellis     1 Trefan Street Apt. E, Toronto ON, M5A 3A9
rae@utcs.toronto.edu        ||               rae@alias.com
CDA0610@applelink.apple.com ||      +1 416 362 9181 [work]
