Tuesday, October 4, 2011

downcasting in c++

c++ downcasting example
Downcasting is when you convert from a base class pointer to a derived class pointer. I have written a function called BaseToChild which does various kinds of downcasting based on the CastType enumeration parameter passed to it. Obviously I cannot use const_cast here because we are casting across unlike types. Unsafe downcasting I have pBase1 which holds a Base object and I am now going to attempt to downcast it to a Child object. Obviously this is unsafe and something which I really shouldn't be doing. I called BaseToChild four times, once for each type of cast (const_cast not usable here). I only show the sample code for dynamic_cast, but the code for the other three casts are very much similar. I summarize my results in the table below.

Cast
Result
Notes
dynamic_cast
Failure
Fails and returns NULL
static_cast
Success
Unsafe cast made
reinterpret_cast
Success
Unsafe cast made

Safe downcasting Alright now we have the Base object holding a Child object. Now it's perfectly safe to downcast to the derived class. Again I called BaseToChild four times, once for each type of cast except const_cast. The table below shows the results I got.

Cast
Result
Notes
dynamic_cast
Success
Safe cast
static_cast
Success
Safe cast
reinterpret_cast
Success
Safe cast

Recommendation for downcasting 

If you are absolutely sure that the cast is going to be safe, you can use any of the three cast operators above, but I'd suggest that you use static_cast because that'd be the most efficient way of casting. If you are even a microscopic percentage unsure as to the safety of your cast, you must simply *avoid* static_cast and reinterpret_cast both of which are quite dangerous here. You may use either dynamic_cast depending on whether you like to check for NULL or you like to have an exception raised and handled.

No comments:

Post a Comment