HP aC++/HP C Programmer's Guide (B3901-90036; A.06.26; September 2011)

cases it may not be desirable, for example, some base class interfaces might be too big
if all derived class functionality is included.
You can rewrite the previous example, using virtual functions, as:
class Base {
virtual void outputType() { cout << Base Object\n; }
// additional class details omitted
};
class Derived : public Base {
virtual void outputType() { cout << Derived Object\n; }
// additional class details omitted
};
int main ()
{
Base *p;
// code which does either
// p = new Base; or
// p = new Derived;
p->outputType();
}
A second alternative is to use a dynamic cast. In many cases, this alternative is less
desirable than using virtual functions, but it is better than a typeid switch statement in
nearly every case. There is a subtle difference between this alternative and the typeid
switch statement above. The typeid operation allows access to the exact type of an object;
a dynamic cast returns a non-zero result for the target type or a type publicly derived
from it.
You can rewrite the previous example as follows using dynamic casts:
class Base {
virtual void f(); // Must have a virtual function to
// be a polymorphic type.
// additional class details omitted
};
class Derived : public Base {
// class details omitted
};
void Base::f()
{
// Define function from Base.
}
int main ()
HP aC++ Keywords 183