What's the difference between how virtual and non-virtual member functions are called?

前端 未结 3 537
囚心锁ツ
囚心锁ツ 2021-01-17 01:13
#include
using namespace std;
int main(){
    class c1{

        public:
         int func(){
            cout<<\"in the  c1\";
         }

            


        
3条回答
  •  醉酒成梦
    2021-01-17 01:41

    See http://www.cs.technion.ac.il/users/yechiel/c++-faq/dyn-binding.html , And I quote:

    Non-virtual member functions are resolved statically. That is, the member function is selected statically (at compile-time) based on the type of the pointer (or reference) to the object.

    In contrast, virtual member functions are resolved dynamically (at run-time). That is, the member function is selected dynamically (at run-time) based on the type of the object, not the type of the pointer/reference to that object. This is called "dynamic binding." Most compilers use some variant of the following technique: if the object has one or more virtual functions, the compiler puts a hidden pointer in the object called a "virtual-pointer" or "v-pointer." This v-pointer points to a global table called the "virtual-table" or "v-table."

提交回复
热议问题