Re: Variables disappearing from scope when i don't want them to
The Cool Giraffe <giraffen@viltersten.com> wrote:
Suppose there's an abstract base class and two inheriting
classes declared as follows.
class Shape {double sizeA;};
class Ellipse : Shape {double sizeB};
class Rect : Shape {double sizeC};
In our program we will have a pointer to a shape but we
don't know which one yet. So, we declare it as follows.
Shape *shapy;
Then, i'd like to do this:
shapy = new Ellipse ();
shapy->sizeA = 4;
shapy->sizeB = 5;
or this:
shapy = new Rect ();
shapy->sizeA = 4;
shapy->sizeC = 5;
but, while the first two lines work fine (i.e. the computer
finds the sizeA and can handle the pointers to Ellipse
and Rect), the implementation specific variables are not
reachable. How can i solve this without binding shapy to
Ellipse or Rect explicitly?
This isn't the code you tried to compile. Your real code almost
certainly makes sizeA, sizeB and sizeC public members, or you wouldn't
have gotten as far as you had.
Anyway, back to your question:
Without casting, you mean? You can't.
As far as the compiler knows, 'shapy' is a Shape*. It has no knowledge
whatsoever that it may in fact be an Ellipse or Rect. It knows only the
interface to Shape, which has sizeA. To get at sizeB you must have an
Ellipse, to get at sizeC you must have a Rect.
You can get this by doing:
Ellipse *e = new Ellipse();
e->sizeA = 4;
e->sizeB = 5;
shapy = e;
Keith
--
Keith Davies "Sometimes my brain is a very strange
keith.davies@kjdavies.org to live in."
keith.davies@gmail.com -- Dana Smith
http://www.kjdavies.org/