Does every class have virtual function table in C++

纵然是瞬间 提交于 2019-12-14 03:49:47

问题


Does every class have virtual function table in C++?

I know virtual table is for polymorphism. Class with virtual functions must have v-table. But how about class has no virtual function? Or how about class has no base class?


回答1:


The language specification of C++ does not define what a "vtable" is, or which classes need one.

A particular implementation of C++ in a compiler often uses a vtable to implement virtual methods. If a class has no virtual methods (and no superclasses with virtual methods), then the compiler may omit the vtable. However, keep in mind this is purely a compiler implementation decision, and not required by the standard.




回答2:


As a non-standard rule of thumb (vtables are not dictated by the standard) which applies to virtually all compilers:

Only classes with virtual member functions and/or a virtual destructor have a vtable. Other classes not. This conforms to the general rule in C++ "pay for what you use".

Of course this puts you into an important responsibility: Is your class to be deleted polymorphically? I.e., will it be used as a public base class and be deleted through it? Then make the destructor virtual.




回答3:


C++ language as such doesn't talk about how virtual functions needs to be implemented i.e. it can using vtables or any other mechanism. Having said that, generally it is implemented using v-table, and this v-table is created only if the class contains virtual functions.




回答4:


v-table holds the function's address in it. This table will hold the function address of all the virtual functions that are defined in the base class. Based on the actual object type, this address changes and the exact function is called.

If the class does not inherits any of the class with virtual function, it need not hold any v-table. All the functions calls will be linked compile time.



来源:https://stackoverflow.com/questions/9477145/does-every-class-have-virtual-function-table-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!