HP aC++/HP C A.06.25 Programmer's Guide
diagnostic output. It also might be used to perform some standard service on an object
such as via a database or I/O system.
typeid Example
Following is an example of the typeid keyword:
# include <iostream.h>
# include <typeinfo>
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 ()
{
Base *p;
// Code which does either
// p = new Base; or
// p = new Derived;
// Note that this is NOT a good design for this
// functionality Virtual functions would be better.
if (typeid(*p) == typeid(Base))
cout << “Base Object\n”;
else if (typeid(*p) == typeid(Derived))
cout << “Derived Object\n”;
else
cout << “Another Kind of Object\n”;
}
If a typeid operation is performed on an expression that is not a polymorphic type
(a class which declares or inherits a virtual function), the operation returns the static
(compile-time) type of the expression. In the example above, if class Base did not include
the virtual function f, typeid(p) would always yield the type Base. The style of
programming used in the above example is called a typeid switch statement. It is not
recommended. One alternative is to use a virtual function in a base class specialized
in each of its derived classes. In some cases, this may not be possible, for example, when
192 Standardizing Your Code