Difference and usage of static_cast dynamic_cast reinterpret_cast const_cast

  • 2020-04-02 01:39:53
  • OfStack

1. Static_cast Pointers to classes can only be converted to classes that are inherited. For normal Pointers, you can only convert between void* and other Pointers. It also converts simple types, such as int to char, etc. Number to pointer conversion cannot be provided. Conversions between Pointers of different types such as int* to char* cannot be provided.

2. Dynamic_cast Provide safe conversions if there is no inheritance between the two Pointers the conversions will fail to return null Pointers, and if you provide an incorrect pointer the memory access exception will occur because it will compare the two types of vtable. The pointer to the vtable is usually in the first four bytes of the object pointer, so you go to the wrong address and you're bound to get an exception.

3. The reinterpret_cast Provides number to pointer conversion such as void* to int. Provides casts of different types of Pointers such as int* to char*. Int to char conversion is not provided. However, it cannot be used to handle class pointer conversion. It will not automatically adjust the pointer.

4. Const_cast Converts a const pointer to a non-const, preferably not with this conversion.


Related articles: