user997112
user997112

Reputation: 30615

C++ (Virtual) Function Table

Is the C++ vtable only used for determining which section of code should be executed when a call is made to a virtual function, or does it have other uses at run-time?

On wikipedia it lists "dynamic dispatch" as a reason, but doesn't go into further details for C++.....

Upvotes: 2

Views: 366

Answers (2)

Peter Ritchie
Peter Ritchie

Reputation: 35881

The C++ vtable is simply a lookup table for function pointers. Any specific C++ implementation may use the vtable for other things; but that is implementation (and version) specific. Relying on the vtable for anything other than C++ to invoke your virtual methods is a really bad idea.

Upvotes: 0

Matteo Italia
Matteo Italia

Reputation: 126787

Some implementations place a pointer to information used by RTTI code (typeid, dynamic_cast, ...) in a slot of the vtable (see here about the Itanium ABI, on which the g++ ABI is based).

(actually, if you read the Itanium ABI specification it's slightly more convoluted, but this is the general idea)

Also, as you can see from the linked document, there's some more stuff to access the data of the base class, perform pointer adjustment when calling base-class methods, ..., mostly stuff needed in "complicated" object hierarchies (multiple inheritance, virtual base classes, ...), as in the classic single inheritance scenario the layout of a derived class is straightforward and doesn't require all this fuss.

Upvotes: 4

Related Questions