Calling derived class's methods from pointer to base class via reinterpret_casting the method pointer. Is this UB?

106 Views Asked by At

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

There are 1 best solutions below

1
M.M On

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.