Is it safe to “upcast” a method pointer and use it with base class pointer?

后端 未结 1 540
温柔的废话
温柔的废话 2020-12-16 01:22

Let\'s say I have a pointer type that can hold the address of a base class method. Can I assign the address of a subclass method to it and expect it to work correctly? In my

1条回答
  •  一向
    一向 (楼主)
    2020-12-16 02:00

    It's valid.

    If class B contains the original member,

    B doesn't contain D::Foo, so no.

    or is a base [...] of the class containing the original member

    B is a base of D, so this holds. As a result:

    the resulting pointer to member points to the original member

    Clause 5.2.9 9 says you can upcast only if you can also downcast, as specified in § 4.11:

    An rvalue of type “pointer to member of B of type cv T,” where B is a class type, can be converted to an rvalue of type “pointer to member of D of type cv T,” where D is a derived class (clause 10) of B. If B is an inaccessible (clause 11), ambiguous (10.2) or virtual (10.1) base class of D, a program that necessitates this conversion is ill-formed.

    This just says you can downcast as long as B is accessible, isn't virtual and only appears once in D's inheritance diagram.

    The danger inherent in upcasting method pointers is that you could call mp on an object whose actual type is B. As long as a code block that deals with D::* also deals with D*, you can avoid this.

    0 讨论(0)
提交回复
热议问题