Thursday, June 06, 2024

RTTI vs getSubClass()

I was doing OS development when I started learning C++, and then I went on with DS development. In both case, the amount of memory you're willing to devote to the code of your program is limited. I remember I heard of -fno-rtti on the osdev wiki and thought "well, yeah, that makes sense". I'd rather not have something I know almost nothing about making key decisions on my objects when I have an instance of SomethingGeneric and want to turn it into SomethingMoreSpecific to use its advanced API for any purpose.

Here and now, I had something where I'd be in a similar situation, but there's actually just one way it could be more specific. I had added SomethingGeneric::isSpecific() virtual function and used it to see whether I should reinterpret_cast<SomethingMoreSpecific&>(myGeneric) here and there. Then the colleague who reviewed suggested it might better be a dynamic_cast<SomethingMoreSpecific&> instead ... or we could have SomethingGeneric::getSpecific() instead. and, well, yeah. I like that.

That wouldn't work with SomethingImplementedWithOpenGL vs. SomethingImplementedWithDirect3D vs. SomethingImplementedWithBlitterAndCopper, but for this use case, it's just fine. I don't have more weight on the virtual table ... I don't depend on unknown run-time ... I don't need to add exceptions catching in case of std::bad_cast ... So long, dynamic_cast: I won't need you, after all.

1 comment:

Björkus "No time_t to die" Dorkus said...

RTTI is an unmitigated disaster in C++. It is one of the core features of C++ that, after their brief foray into the space, WG21 has fairly strongly committed to never having it in any of their standard library interfaces if they can avoid it