CASTING BETWEEN CLASS TYPES

You have seen how you can store the address of a derived class object in a variable that is a pointer to a base class type, so a variable of type CContainer* can store the address of a CBox object for example. So if you have an address stored in a pointer of type CContainer*, can you cast it to type CBox*? Indeed, you can, and the dynamic_cast operator is specifically intended for this kind of operation. Here’s how it works:

CContainer* pContainer = new CGlassBox(2.0, 3.0, 4.0);
CBox* pBox = dynamic_cast<CBox*>( pContainer);
CGlassBox* pGlassBox = dynamic_cast<CGlassBox*>( pContainer);

The first statement stores the address of the CGlassBox object created on the heap in a base class pointer of type CContainer*. The second statement casts pContainer up the class hierarchy to type CBox*. The third statement casts the address in pContainer to its actual type, CGlassBox*.

You can apply the dynamic_cast operator to references as well as pointers. The difference between dynamic_cast and static_cast is that dynamic_cast checks the validity of a cast at run time, whereas the static_cast operator does not. If a dynamic_cast operation is not valid, the result is null. The compiler relies on the programmer for the validity of a static_cast operation, so you should always use dynamic_cast for casting up and down a class hierarchy and check for a nullptr result if you want to avoid abrupt termination of your program.

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.