Reputation: 151
I read that an abstract class can still have a table. But I'm confused on how many entries it would have in its vtable. For example, if my abstract class was:
class Circle(){
virtual void draw() = 0;
}
then how many entries would be in its vtable? Also, am I correct in saying that this abstract class has 1 entry in its vtable? Thanks for any help.
class Circle(){
virtual double a{ return 0.0; }
virtual void draw() = 0;
}
Upvotes: 0
Views: 327
Reputation: 45674
Well, vtables are an implementation-detail, though an ubiquitous one.
As neither Circle
's ctor-body nor dtor-body calls any of its functions, especially none calling virtual ones, and it is abstract due to the pure virtual function, Circle
's vtable is never used, if it is in fact even created.
Anyway, the theoretical vtable needs at least one entry for the std::type_info
and any other support for dynamic_cast
, one for each virtual function, and if the dtor is virtual, two for that (one just for the dtor, one for dtor + deallocation with delete
).
Which comes to at least 3 entries (2 virtual functions + RTTI) for your second example.
Upvotes: 2
Reputation: 72044
First, vtables are an implementation detail. As long as you're not doing really weird things, you should ignore their existence.
Second, even though all compilers use vtables to implement virtual dispatch, there are differences in how they do it. For some, a vtable entry is just a function pointer; for others, it's a pointer an an offset. Some compilers have one entry for a virtual destructor, some have two, or even more. And some add a new entry for a covariantly overriden function, while others might not.
The bottom line is that you shouldn't, in general, worry about this issue. If you are interested in implementation details, you could for example read the Itanium C++ ABI, which is what Linux compilers generally follow.
Upvotes: 4
Reputation: 76418
Every virtual function can be overridden. The compiler has to build in some mechanism to dynamically dispatch calls to each virtual function so that the code calls the right overriding version, which depends on the actual type of the object. That mechanism is typically a vtable, and there has to be one entry for each virtual function. So the first example would have one entry, and the second would have two. Note that marking a function as pure virtual does not affect this; it still has to be dynamically dispatched.
Upvotes: 6