4.2 Down casting

Dynamic down casting can fail. Let us consider the following example:

class A
{
  // defn containing at least one virtual method
};

class B : public A
{
  // defns for B
};

class C : public A
{
  // defns for C
};

Here, we have both classes B and C derived from A. Class A has at least one virtual methods to make it polymorphic. Now, consider the following code:

{
  A *pA;
  B myB, *pB;
  C myC, *pC;

  pA = &myC; // a cast is implicit here
  pB = dynamic_cast<B*>(pA);
  pC = dynamic_cast<C*>(pA);
  if (pB)
  {
    // do something with pB
  }
  else if (pC)
  {
    // do something with pC
  }
}

Because a failed dynamic cast returns a NULL pointer, we can use that as a hint to determine the actual type of an object pointed to by a superclass pointer.



Copyright © 2006-10-12 by Tak Auyeung