[LC++]Playing with polymorphism

Carlo Wood carlo at alinoe.com
Mon Apr 19 23:40:01 UTC 2004


On Mon, Apr 19, 2004 at 07:41:16AM +0200, 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 basic error you make is using a global variable.
Globals are evil.

As soon as you try to make the global part of a class, and therefore
also the load() function, you notice that it makes no sense to mix
A* and B* there: the global is a B* and THUS you know about B already;
there is no need to go via A*.

The practical error is that you cannot assign a value to an A* when
that really is a B*.

I understand you basically want this:

  B b1;
  A* a1 = &b1;
  B* b2 = dynamic_cast<B*>(a1);
  assert(b2);

  assert(b2 == &b1);

  The above works if B is derived from A and they are polymorph (A has a virtual destructor).

-- 
Carlo Wood <carlo at alinoe.com>



More information about the tuxCPProgramming mailing list