C++ inheritance and member function pointers

前端 未结 8 690
忘了有多久
忘了有多久 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条回答
  • 2020-12-03 01:25

    I believe so. Since the function pointer uses the signature to identify itself, the base/derived behavior would rely on whatever object you called it on.

    0 讨论(0)
  • 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.

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