Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an abstract classes have a VTABLE?

Tags:

c++

Do we have virtual table for an abstract class?

like image 734
Vijay Avatar asked Apr 07 '10 12:04

Vijay


People also ask

Does every class have a vtable?

Only classes with virtual member functions and/or a virtual destructor have a vtable.

Does every object have a vtable?

All classes with a virtual method will have a single vtable that is shared by all objects of the class. Each object instance will have a pointer to that vtable (that's how the vtable is found), typically called a vptr. The compiler implicitly generates code to initialize the vptr in the constructor.

Can abstract class have non virtual function?

Abstract classes (apart from pure virtual functions) can have member variables, non-virtual functions, regular virtual functions, static functions, etc.

Can abstract class have data members in C++?

No objects of an abstract class can be created (except for base subobjects of a class derived from it) and no non-static data members whose type is an abstract class can be declared.


2 Answers

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.

like image 191
interjay Avatar answered Oct 19 '22 16:10

interjay


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.

like image 31
Ofek Shilon Avatar answered Oct 19 '22 16:10

Ofek Shilon