[LC++]Playing with polymorphism

Paul Gearon gearon at ieee.org
Mon Apr 19 15:24:02 UTC 2004


Peter Poulsen wrote:
> I have this very small program (http://www.pgpnet.dk/test.cc). It is a
> bit hard to explain what it does but the program is _very_ small and you
> will probably not have any problems understanding it. What I don't
> understand is why I have to cast a B pointer to an A pointer when
> calling load as B is a descendent of A? Can anybody explain that to me?

The reason that the code fails is because the cast (a C-style cast) is
illegal, but because you used a C-style cast the compiler let you just go
ahead and do it.  ie. you shot yourself in the foot.  :-)  Try printing out
the address of "b" before you call the function "load", and then print out the
address of "a" inside the function.  You'll see that you get 2 different
addresses!

References are sort of a shorthand for doing pointers.  Your original code was:
void load(A*& a){ a = global; }
..... load(b); .....

The reason this didn't compile is for the same reason that the following won't
compile:
void load(A** a){ *a = global; }
..... load(&b); .....


Sure, "B" inherits from "A", and so you can say "b is an A", but B* does not
inherit from A*.  If this were legal then what would happen if you declared
"C" to inherit from A?  Passing an object of type C into the load function is
clearly illegal.

Try re-thinking your approach.  I don't know what your original program is
supposed to do, but I find it strange that you'd have a function that wants to
take a pointer to derived class, masquerading as a base class pointer, and
then set it to something of the correct type.  You'd always need to test the
type of pointer you had in order to work out what you are allowed to make it
point to.  If you really need this then templates are probably more appropriate.



More information about the tuxCPProgramming mailing list