HP aC++/HP C Programmer's Guide (B3901-90036; A.06.26; September 2011)
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.
The syntax of conditions allows declarations in them. For example:
class Base {
virtual void f(); // Make Base a polymorphic type
// other class details omitted
};
class Derived : public Base {
public:
void derivedFunction();
// other class details omitted
};
void Base::f()
{
// Define Base function.
}
void Derived::derivedFunction()
{
}
int main()
{
Base *p = new Derived;
// details omitted
if (Derived *q = dynamic_cast<Derived *> (p))
q->derivedFunction(); // use derived function
}
You can use dynamic casts with references as well. Since a reference cannot be zero,
when the cast fails, it raises a Bad_cast exception. Before the implementation of the
dynamic cast operator, you could not cast from a virtual base class to one of its derived
classes because there was not enough information in the object at runtime to do this cast.
Once runtime type identification was added, however, the information stored in a
polymorphic virtual base class is sufficient to allow a dynamic cast from this base class
to one of its derived classes. For example:
class Base1 {
// Not a polymorphic type.
// additional class details omitted
};
class Base2 {
virtual void f(); // Make Base2 polymorphic.
// additional class details
174 Standardizing Your Code