zpeng
zpeng

Reputation: 101

member function pointer conversion

#include <iostream>
using namespace std;


class A {
};
typedef void (A::*funA)(int);

class B : public A {
public:
void m(int) {std::cout << "mm" << std::endl; }
void n(int) { std::cout << "nn"<<std::endl; }   
};
typedef void (B::*funB)(int);

class C : public B {
public:
void g(int) {std::cout << "gg" << std::endl; }
void h(int) { std::cout << "hh"<<std::endl; }
};
typedef void (C::*funC)(int);

int main() {
funB f = static_cast<funB>(&C::m);
A* pa = new A;
(pa->*(static_cast<funA>(f)))(2);
return 0;
}

gcc compile and output "mm". But why can this work? Class A in fact don't define any function. It seems the class can use its base class or derived class function by this way, even though it doesn't define them.

Upvotes: 0

Views: 68

Answers (1)

Brian Bi
Brian Bi

Reputation: 119562

Since A doesn't contain the member that f refers to, the behaviour is undefined.

The probable reason why it works anyway is that the function B::m doesn't touch the this pointer, so it doesn't "notice" when it's called on an object of the wrong type. Also, A and B are not polymorphic, so dereferencing the pointer-to-member and calling doesn't require examining any vptr.

Upvotes: 2

Related Questions