logoalt Hacker News

gignicoyesterday at 10:10 PM3 repliesview on HN

> Under the hood, a virtual table (vtable) is created for each class, and a pointer (vptr) to the vtable is added to each instance.

Coming from C++ I assumed this was the only way but Rust has an interesting approach where the single objects do not pay any cost because virtual dispatch is handled by fat pointers. So you carry around the `vptr` in fat pointers (`&dyn MyTrait`) only when needed, not in every instance.


Replies

cataphractyesterday at 11:26 PM

There have been type-erasure libraries in c++ for a longish time that allow choosing inline vtables and inline storage. It's definitely been a widely talked about technique for at least 10 years (I see talks about Dyno from 2017).

anon291today at 12:46 AM

This is the standard type class approach. Haskell does the same thing.

dalvrosayesterday at 10:18 PM

Good point, thanks for sharing!