HP aC++/HP C A.06.25 Programmer's Guide

the base class is provided by a library for which source code is not available. In other
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.
}
HP aC++ Keywords 193