问题
With a pointer to an object of a derived type assigned to a pointer of its base class, I've found that you can reinterpet_cast a method from the derived class to a pointer of the base class, even if the base class doesn't have any such function (virtual, hidden, or otherwise). And it can be dereferenced and called from there and it "just works". But I'd like to make sure it's not UB. Is this UB? Is it portable?
Compilable Example:
#include <cstdio>
struct A { /* no foo method */ };
struct B : public A { void foo(void){printf("foo");} };
typedef void (B::*B_FOO_PTR)( void );
typedef void (A::*A_FOO_PTR)( void );
int main ( void ) {
B b;
A* a = &b;
// address of a and b are identical
B_FOO_PTR b_ptr = &B::foo;
// (a->*b_ptr)(); // COMPILE ERROR: calling B method from A. Not Allowed, but...
A_FOO_PTR a_ptr = reinterpret_cast<A_FOO_PTR>(b_ptr);
(a->*a_ptr)(); // works, outputs "foo"
return 0;
}
回答1:
This is undefined behaviour. The only pointer-to-member function conversions where you can call the result are:
- round-trip conversion, and
- pointer-to-member-of-base to pointer-to-member-of-derived.
You attempt the inverse of the second point, which is excluded from this list.
来源:https://stackoverflow.com/questions/56943547/calling-derived-classs-methods-from-pointer-to-base-class-via-reinterpret-casti