Search code examples
c++castingpolymorphismcoercion

Is coercion static or dynamic polymorphism?


Parametric polymorphism and overloading are static polymorphism, because the compiler knows at compile-time which function to call. Subclassing is dynamic polimorphism, beause the function gets determined at run-time. But what is coercion (implicit casting)? Static or dynamic polimorphism? The compiler knows at compile time which function to call, but the actual cast happens at run-time. Or is that statement wrong?


Solution

  • Runtime polymorphism involves (potentially) several distinct bits of machine code being selected from based on some runtime data related to the runtime type of data involved, and that selection happens at runtime. (I say potentially because you can use virtual dispatch when there's only one concrete derived type, but the runtime mechanism is there to support further types).

    With coercion, only one machine code path is required to massage the data into some other type needed by the code then executed - there is no runtime type-based selection of the code to execute. What that one machine code path should be is decided at compile time.