how c++ implements the polymorphism internally?

后端 未结 4 1377
耶瑟儿~
耶瑟儿~ 2020-12-31 20:02

Respected Sir!

i should tell you that what i know and what i don\'t know about the asked question so that you can address the weak area of my understanding.

4条回答
  •  一个人的身影
    2020-12-31 20:37

    Since show is declared virtual in the person class, the compiler will not hard-code the method call like it would do for a non-virtual method, it will instead compile a lookup in the V-table in order to retrieve the right function.

    So ptr->show() will be compiled as ptr->vtable['show']() which means "search the function pointer that corresponds to method show and execute it".

    Since at runtime, ptr points to an object of class teacher, the vtable slot for show contains a pointer to the method show in the class teacher. That is why the right method is executed.

    Actually, lookup in the V-table is not done using strings but using numeric method identifiers in order to be as fast as possible.

提交回复
热议问题