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

不羁的心 提交于 2019-12-24 06:34:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!