Saturday, August 13, 2016

C++ How to make cross-cast correctly?

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.

References


C++ What does static_cast can do?

The behavior of static cast is well described in many sources. Below is the code example that could reveal some usage cases.
The output of the program execution is the next:

static_cast<int>(1.0) = 1
static_cast<int>(0xFFFFFFFFU) = -1
static_cast<int>(0xFF11FFFFFFULL) = 0x11FFFFFF
static_cast<float>(5) = 5.000000
static_cast<unsigned int>(-1) = 4294967295
(d1.*d1_func_ptr)() returns 1
(d12.*d12_func_ptr)() returns 2
(d12.*d12_func_ptr)() returns 1
(d1.*d1_func_ptr)() returns 2