Casting

The C++ language provides that if a class is derived from a base class containing virtual functions, a pointer to that base class type can be used to call the implementations of the virtual functions residing in the derived class object. A class containing virtual functions is sometimes called a “polymorphic class.”

Since a derived class completely contains the definitions of all the base classes from which it is derived, it is safe to cast a pointer up the class hierarchy to any of these base classes. Given a pointer to a base class, it might be safe to cast the pointer down the hierarchy. It is safe if the object being pointed to is actually of a type derived from the base class. In this case, the actual object is said to be the “complete object.” The pointer to the base class is said to point to a “subobject” of the complete object. For example, consider the class hierarchy shown in Figure 4.3:

Figure 4.3   Class Hierarchy

An object of type C could be visualized as shown in Figure 4.4:

Figure 4.4   Class C with B Subobject and A Subobject

Given an instance of class C, there is a B subobject and an A subobject. The instance of C, including the A and B subobjects, is the “complete object.”

Using run-time type information, it is possible to check whether a pointer actually points to a complete object and can be safely cast to point to another object in its hierarchy. The dynamic_cast operator can be used to make these types of casts. It also performs the run-time check necessary to make the operation safe.