Sunday, November 29, 2009


dynamic_cast can be used only with pointers and references to objects.

Therefore, dynamic_cast is always successful when we cast a class to one of its base classes

Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.

dynamic_cast requires the Run-Time Type Information (RTTI) to keep track of dynamic types.

class CBase { };
class CDerived: public CBase { };

CBase b; CBase* pb;
CDerived d; CDerived* pd;

pb = dynamic_cast(&d); // ok: derived-to-base
pd = dynamic_cast(&b); // wrong: base-to-derived
The second conversion in this piece of code would produce a compilation error since base-to-derived conversions are not allowed with dynamic_cast unless the base class is polymorphic.

dynamic_cast can also cast null pointers even between pointers to unrelated classes, and can also cast pointers of any type to void pointers (void*).

No comments:

Post a Comment