Search code examples
c++castingparent-childdynamic-castreinterpret-cast

What Type of Cast to Go from Parent to Child?


This question is about which C++ style cast should be used to make this conversion. I am aware that a C style cast can achieve this.

For the following class structure:

class Foo {};

class Bar : public Foo {};

Say that I am given: Foo* ptr; and I want to cast it to a Bar* which type of cast should I be using? It seems like I must use dynamic_cast as it is:

Used for conversion of polymorphic types

I wanted to avoid dynamic_cast since it is a run time cast.


Solution

  • You are correct that dynamic_cast is usually the most appropriate for this situation. However, if you know that the pointer is actually pointing to an object of the derived class, you can use static_cast for the conversion. If you're wrong and the pointer is not the derived class, you'll get undefined behavior.