Do we have virtual table for开发者_如何学JAVA an abstract class?
First of all, usage of vtables is implementation defined and not mandated by the standard.
For implementations that use vtable, the answer is: Yes, usually. You might think that vtable isn't required for abstract classes because the derived class will have its own vtable, but it is needed during construction: While the base class is being constructed, it sets the vtable pointer to its own vtable. Later when the derived class constructor is entered, it will use its own vtable instead.
That said, in some cases this isn't needed and the vtable can be optimized away. For example, MS Visual C++ provides the __declspec(novtable)
flag to disable vtable generation on pure interface classes.
There seems to be a common misconception here, and I think traces of its sources can still be found online. Paul DiLascia wrote sometime in 2000 that -
...see that the compiler still generates a vtable all of whose entries are NULL and still generates code to initialize the vtable in the constructor or destructor for A.
That may actually have been true then, but certainly isn't now.
Yes, abstract classes do have vtables, also with pure abstract methods (these can actually be implemented and called), and yes - their constructor does initialize the pure entries to a specified value. For VC++ at least, that value is in the address of the CRT function _purecall. You can in fact control that value, either by overloading purecall yourself or using _set_purecall_handler.
We have a virtual table for a class which has atleast one virtual function. that virtual function can also be pure. this means. an abstact class can have a vtable.
in case of abstact classes the vtable entry will be NULL. when ever you try to instantiate a abstract class it will check in tha vtable and check for a NULL value is present or not. if NULL is present the compiler will throw an error.
精彩评论