C++ inheritance and member function pointers

Viewed 26548

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 three classes X, Y, Z in order of inheritance. Y therefore has a base class X and a derived class Z.

Now we can define a member function pointer p for class Y. This is written as:

void (Y::*p)();

(For simplicity, I'll assume we're only interested in functions with the signature void f() )

This pointer p can now be used to point to member functions of class Y.

This question (two questions, really) is then:

  1. Can p be used to point to a function in the derived class Z?
  2. Can p be used to point to a function in the base class X?
8 Answers

I'm not 100% sure what you are asking, but here is an example that works with virtual functions:

#include <iostream>
using namespace std;

class A { 
public:
    virtual void foo() { cout << "A::foo\n"; }
};
class B : public A {
public:
    virtual void foo() { cout << "B::foo\n"; }
};

int main()
{
    void (A::*bar)() = &A::foo;
    (A().*bar)();
    (B().*bar)();
    return 0;
}

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.

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]

Related