C++ inheritance and member function pointers

前端 未结 8 807
忘了有多久
忘了有多久 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:07

    My experimentation revealed the following: Warning - this might be undefined behaviour. It would be helpful if someone could provide a definitive reference.

    1. This worked, but required a cast when assigning the derived member function to p.
    2. This also worked, but required extra casts when dereferencing p.

    If we're feeling really ambitious we could ask if p can be used to point to member functions of unrelated classes. I didn't try it, but the FastDelegate page linked in dagorym's answer suggests it's possible.

    In conclusion, I'll try to avoid using member function pointers in this way. Passages like the following don't inspire confidence:

    Casting between member function pointers is an extremely murky area. During the standardization of C++, there was a lot of discussion about whether you should be able to cast a member function pointer from one class to a member function pointer of a base or derived class, and whether you could cast between unrelated classes. By the time the standards committee made up their mind, different compiler vendors had already made implementation decisions which had locked them into different answers to these questions. [FastDelegate article]

提交回复
热议问题