Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

c++ - Difference between calling of virtual function and non virtual function?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Though virtualism/dynamic dispatch is strictly implementation defined, most(read all known) compilers implement it by using vptr and vtable.

Having said that, the difference between calling a non virtual function and virtual function is:

Non-virtual functions are resolved statically at Compile-time, While Virtual functions are resolved dynamically at Run-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 fetch call 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:

fetch-call

The compiler needs to fetch address of the function and then call it.

While in case of virtual functions the sequence is:

fetch-fetch-call

The compiler needs to fetch the vptr from the this, then fetch the address of the function from the vptr and then call the 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...