Why runtime ploymorphism is required ? give a real example that "why it came into existence when we have compile time polymorphism??" As mainting the runtime polymorphism requires lot of overhead of maintaining virtual tables and pointers. What are the benefits of "runtime polymorphism" over compile time with a good example. As runtime decision can be made compile/static time if we know the process already and with user inputs. Why we are compromising with performance and doing runtime polymorphism?? Please give a real and good example

  • 1
    As many, you overestimate the performance impact of virtual functions. You ask for examples which is offtopic here; just google that; there are plenty of reasons. – marstato Mar 28 '17 at 12:38
  • polymorphism exists for 2 decades (and maybe more I'm no expert in the domain), it had plenty of time to be properly optimized to reduced memory footprints, increase performance,... Whatever you code yourself, you will be way far of that those who wrote the compiler, its optimizations and the handling polymorphism. – Walfrat Mar 28 '17 at 12:57

As runtime decision can be made compile/static time if we know the process already and with user inputs

No, we can't make those decisions statically. We cannot even decide something as trivial as whether the program will halt or not.

In fact, IFF we could decide which function we were going to call, then we could automatically turn runtime polymorphism into compile-time polymorphism. This is called de-virtualization and C++ compilers already do this as an optimization, but it doesn't always work, because, you guessed it, it is equivalent to solving the Halting Problem.

Note: a dynamic compiler can eliminate dynamic dispatch and thus enable inlining, for example. A de-optimizing dynamic compiler can even go one step further and perform Speculative Inlining: it can simply inline the method under the assumption that the lookup will always lead to the same method, and when it turns out that this assumption was wrong, the compiler can simply de-inline the method (and then potentially inline the new method again). Or it can build a cache of previously seen types and the corresponding methods; it can then inline the methods into that cache, inline the cache into the call site, or both. Keywords to look for are Monomorphic Inline Cache, Duomorphic Inline Cache, and Polymorphic Inline Cache; my description is extremely simplified. This general area is called Adaptive Optimization.

Not the answer you're looking for? Browse other questions tagged or ask your own question.