Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can C++ virtual functions be implemented except vtable? [duplicate]

Possible Duplicate:
A question about virtual mechanism in C++

Is using vtable the only way to implement virtual member functions mechanism in C++? What other ways exist?

like image 682
sharptooth Avatar asked Mar 24 '11 10:03

sharptooth


People also ask

How are virtual functions implemented in C?

There is no way to implement virtual functions in plain C, because C has no notion of inheritance. Update: As is discussed in the comments below, it is possible to do something similar to virtual functions in straight C using structures and function pointers.

How is vtable implemented?

To implement virtual functions, C++ uses a special form of late binding known as the virtual table. The virtual table is a lookup table of functions used to resolve function calls in a dynamic/late binding manner.

Does vtable contain non virtual functions?

No. A vtable only contains pointers to virtual functions in the same class or file.

What is the difference between virtual functions and Vtables?

For every class that contains virtual functions, the compiler constructs a virtual table, a.k.a vtable. The vtable contains an entry for each virtual function accessible by the class and stores a pointer to its definition. Only the most specific function definition callable by the class is stored in the vtable.


1 Answers

Technically, all that's required for dynamic dispatch is the ability to identify the dynamic type of an object, given a pointer to it. Thus, any sort of hidden (or not-so-hidden) typeid field would work.

Dynamic dispatch would use that typeid to find the associated functions. That association could be a hastable or an array where typeid is the index, or any other suitable relationship. vptr just happens to be the way to achieve this in the least number of steps.

like image 91
Cubbi Avatar answered Sep 28 '22 10:09

Cubbi