On Tuesday, 6 March 2018 at 21:20:22 UTC, Henrik wrote:
Does anyone know if D is using the vtable implementation for virtual functions just like most C++ compilers?

Yes, except without multiple inheritance / virtual inheritance.

If yes, can someone explain the advantages of this strategy? A function pointer in C is regarded as expensive because of missing inlining, but a double indirection through a vtable just looks insane - if there aren't really good reasons for such an implementation.

Without measuring, I'd tend to agree with you that it should be more expensive (let's not use the arguments that "this part of memory will be hot" which means it will take a share of cache that could go to something else).

I guess the reason is simple: low overhead with regards to layout (only a pointer gets added to each instance). The v-table point itself to TypeInfo so you hide this pointer too.
TypeInfo is a bit like RTTI in the C++ world.

Note that even in C++ if a virtual call is expensive in the profiler you can switch on a type tag and devirtualize by casting (virtual functions are only expensive when the runtime type is unknown to the compiler).

The alternative layout is to embed the v-table in each object when priming a new object, and having the TypeInfo pointer in each class instance in addition to a pointer for each virtual method.

Does it make class inheritance or class polymorphism much simpler to implement or what is the reason?

I don't know. Intuitively it doesn't seem much easier with v-table.
COM objects are expected to have such a layout too.

I have worked with C in embedded systems for many years now, and for our modern Linux systems we are using a combination of C and Java today. Java for parts where memory safety is more important than speed/determinism, and C for the critical real time parts. There should exist a language between these worlds, where we can achieve memory safety at relatively small costs. C++ is not really an alternative, and D looks much more pleasant for us C programmers than for example Rust.

If you know enough D maybe you can implement your own virtual functions on top of D structs. It seems no one has made it yet.

Reply via email to