HP aC++/HP C A.06.25 Programmer's Guide
Base b;
Derived d;
p = &b;
q = dynamic_cast<Derived *> (p); // Yields zero.
p = &d;
q = dynamic_cast<Derived *> (p); // Yields p treated
// as a derived pointer.
}
Static and dynamic casts are used to move within a class hierarchy. Static casts use only
static (compile-time) information to do the conversions. In the example above, if p is
really pointing to an object of type Derived, either a static or dynamic cast of p to q
yields the same result. This is also true if p were the null pointer. But, if p is not pointing
to an object of type Derived, a dynamic cast returns zero, and a static cast returns a
stray pointer. Dynamic casts must be done to a pointer or reference type. For example,
if the cast above is written as:
q = dynamic_cast <Derived> (p);
The compile time error message is:
The result type of a dynamic cast must be a pointer or reference
to a complete class; the actual type was Derived.
If you attempt a dynamic cast from a non-polymorphic type, you will also get a
compile-time error. For example:
class Base {
// class details omitted
};
class Derived : public Base {
// class details omitted
};
void main()
{
Base *p;
Derived *q;
Base b;
p = &b;
q = dynamic_cast<Derived *> (p);
}
The above generates a compile-time error:
Dynamic down-casts and cross-casts must start from a polymorphic
class (one that contains or inherits a virtual function); but
class Base is not polymorphic.
HP aC++ Keywords 183