How To Use Dynamic Cast
March 31st, 2008Eventhough I would suggest avoiding any type of casting, there are not many situations in C++ where you can omit them. Among the casts, dynamic cast can be very handy and is a normally used one. It is used to convert objects of one type to another related (as a result of inheritance) type.
Eg:
class CMyClass
{
virtual void Foo()
{
}
};
class CMyDerivedClass : public CMyClass
{
void Foo()
{
}
} ;
// Declare a variable of
CMyDerivedClass* myDerivedClassObject = new CMyDerivedClass();
// Call Foo() of derived class
myDerivedClassObject->Foo();
// Call Foo() of the base class
CMyClass* myClass = dynamic_cast<CMyClass*>(myDerivedClassObject);
// Make sure that our program won’t crash
assert(myClass);
myClass->Foo(); // Calls the Foo() in the base class
Note the assert statement. It is always a good practice to use assert just after the dynamic cast, to make sure that you are not going to access an uninitialized object.