Hacker News new | ask | show | jobs
by kccqzy 215 days ago
This is only the case when the language does not distinguish between methods that can be overridden versus those that cannot. C++ gives you the keyword "virtual" to put in front of each member function that you want to opt into this behavior, and in my experience people tend to give it some thought on which should be virtual. So I rarely have this issue in C++. But in languages like Python where everything is overridable, the issue you mention is very real.
3 comments

Good point. In Java and many other languages you can opt out instead... which might make a big difference. Is it more of a "cultural" thing?... again, many frameworks encourage it by design, and so do many courses/tutorials... so those devs would be happy to put "virtual" everywhere in C++
Kotlin switches that back to opt in-- they did as a specific design level thing learning from their observation of how to improve java.
heh, i have seen programmers using virtual everywhere, because they were lazy to use declspec(dll_export) on windows system :)
While in Python everything is overridable, does this show up in practice outside of (testing) frameworks? I feel like this is way more common in Java. My experience in Python is limited to small micro service like backends and data science apps.
I've seen it a lot on Django projects. Maybe I was just unlucky on the Python projects I've joined.
The virtual keyword in c++ is more of a compiler optimization and less of a design decision. C++ doesn't want everyone paying the overhead of virtual function calls like other languages
It still funcions as a design optimization even though that isn't the reason for it.
I think that's an over-simplification. There was pressure on the language to ensure that data structures were compatible with C structs, so avoiding the vtable with simple classes was a win for moving data between these languages.

Of course these days with LTO the whole performance space is somewhat blurred since de-virtualisation can happen across whole applications at link time, and so the presumed performance cost can disappear (even if it wasn't actually a performance issue in reality). It's tough to create hard and fast rules in this case.