Lets take a look at first, what is cross-cast:
Steps made by dynamic_cast
Lets consider next conversion:
Source* ptr = new Actual();
Target* t = dynamic_cast<Target*>(ptr);
There are three steps in performing a dynamic cast.
1. Finding the type and address of the Actual object given the Source pointer (ptr).
2. Determining if the Actual object derives unambiguously from the Target class.
If it does not, null is immediately returned.
3. Computing the offset of the Target class within the Actual class to return a pointer to a Target object.
Conclusion
Cross-casting of pointers in C++ can be done in 3 ways:
- using dynamic_cast;
- using reinterpret_cast (can be done, but result pointer will be incorrect);
- using C-style cast (can be done, but result pointer will be incorrect);
So, there is only one correct way of doing cross-casting in C++ is to use dynamic_cast.
No comments:
Post a Comment