This is in fact an interview question, I can’t figure out the answer. Anyone knows about this?
You can talk about any difference, for example, the data that are push into stack.
This is in fact an interview question, I can’t figure out the answer. Anyone
Share
Though virtualism/dynamic dispatch is strictly implementation defined, most(read all known) compilers implement it by using
vptrandvtable.Having said that, the difference between calling a non virtual function and virtual function is:
Non-virtual functions are resolved
staticallyatCompile-time, While Virtual functions are resolveddynamicallyatRun-time.In order to achieve this flexibility of being able to decide which function to call at run-time,
there is an little overhead in case of virtual functions.
An additional
fetchcall that needs to be performed and it is the overhead/price you pay for using dynamic dispatch.In case of non-virtual function the sequence of calls is:
The compiler needs to
fetchaddress of the function and thencallit.While in case of virtual functions the sequence is:
The compiler needs to
fetchthevptrfrom thethis, thenfetchthe address of the function from thevptrand thencallthe function.This is just a simplified explanation the actual sequence maybe far more complex than this but this is what you really need to know, One does not really need to know the implementation nitty gritty’s.
Good Read:
Inheritance & Virtual Functions