Eventhough 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.
August 28, 2008 at 6:46 am
>> Eventhough I would suggest avoiding any type of casting…
Are you serious?
January 15, 2009 at 5:02 pm
CDerivedClass::Foo will always be called as it is a virtual function.
You can force the compiler to call the base class version but this isn’t how.
Also, assert is only enabled in debug builds. So in a release version it won’t do anything.
Saying assert makes sure your program doesn’t crash misses the point. It makes your program crash.
Finally dynamic_cast won’t fail as you and compiler know that myDerviedObject is-a CMyDerivedClass which is-a CMyClass. So it will never return null (in this example).
January 15, 2009 at 5:39 pm
Of course, assert is not to make a program crash. It will pop up an assertion failure in debug build so that we can fix it before making the release build. (We can use VERIFY in release builds to have the pop up)
As you said, in this example, the dynamic_cast won’t fail.
Thanks a lot for posting the comment. Please keep watching the blog.
May 8, 2009 at 2:32 pm
jHilXX comment6 ,
January 24, 2010 at 3:31 am
The provided example is not a case where you would need a dynamic_cast at all. Upcasting to a base class will always work, and does not require any casts whatsoever.
Upcasting (from Base* to Derived*), on the other hand, could be a good example.
January 24, 2010 at 3:35 am
I’m sorry, mixed the terms upcasting and downcasting; Downcasting would be Base* to Derived* (and that is where you need dynamic cast), while upcasting is treating a Derived* as Base*, which will always work.