C++ inheritance and member function pointers

前端 未结 8 806
忘了有多久
忘了有多久 2020-12-03 00:58

In C++, can member function pointers be used to point to derived (or even base) class members?

EDIT: Perhaps an example will help. Suppose we have a hierarchy of t

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 01:25

    Assume that we have class X, class Y : public X, and class Z : public Y

    You should be able to assign methods for both X, Y to pointers of type void (Y::*p)() but not methods for Z. To see why consider the following:

    void (Y::*p)() = &Z::func; // we pretend this is legal
    Y * y = new Y; // clearly legal
    (y->*p)(); // okay, follows the rules, but what would this mean?
    

    By allowing that assignment we permit the invocation of a method for Z on a Y object which could lead to who knows what. You can make it all work by casting the pointers but that is not safe or guaranteed to work.

提交回复
热议问题