Ways to detect whether a C++ virtual function has been redefined in a derived class

前端 未结 9 1462
不知归路
不知归路 2020-12-01 14:10

In brief: From a C++ base-class pointer which points to an instance of a derived class, how can one determine at run-time whether a non-pure virtual functio

9条回答
  •  孤街浪徒
    2020-12-01 14:32

    For future reference, it turns out that GCC provides this extension: http://gcc.gnu.org/onlinedocs/gcc/Bound-member-functions.html which allows checking if a method was overridden with

    (void*)(obj.*(&Interface::method)) != (void*)(&Interface::method)
    

    ICC supports this extension officially, clang's docs don't mention it but the code works and even compiles without the warning.

    MSVC doesn't support this, though, so there's that.

    Also, it appears to not work with methods defined in the header (i.e. inline) in a separate library if you link to a different version of the library where the implementation has changed. If I interpret the standard correctly, this is undefined behaviour (changing the implementation that is) but if the implementation stays the same, then the address should be unique too. So don't do that with inline methods.

提交回复
热议问题