Hacker News new | ask | show | jobs
by lowercase1 1872 days ago
The source of this capability is hidden in that you had to pass in a Foo to the call site.

If you had done similarly in the struct example by passing in the function Bar to the caller then you could achieve similar functionality by shoving in a Baz function instead.

1 comments

Yeah, but that's the thing: in case of dynamic dispatch in OOP, the function is tied to the argument you're passing. In a typical OOP language, your object carries an extra pointer that's hidden from your view - a pointer to a table of pointers to functions, specific for that object's class. Dynamic dispatch goes through that pointer on the object.

Doing what you describe with a struct would require at least keeping explicit function pointers on the structure; the OOP mechanism described above is a generalization of that.

(There are other, neater approach too, allowing late binding dispatched on the types of more than one argument - see e.g. methods in Common Lisp.)