c++ - Casting a pointer to a method of a derived class to a pointer to a method of a base class -


is legal cast pointer method of derived class pointer method of base class, though base class not declare methods, of "casted" method called through object of type base class, follows:

// works in vs 2008 , g++ 4.5.3 struct base { };  struct fuu : public base {     void bar(){ std::cout << "fuu::bar" << std::endl; }     void bax(){ std::cout << "fuu::bax" << std::endl; } };  struct foo : public base {     void bar(){ std::cout << "foo::bar" << std::endl; }     void bax(){ std::cout << "foo::bax" << std::endl; } };  typedef void (base::*ptrtomethod)();  int main() {     ptrtomethod ptr1 = (ptrtomethod) &foo::bax;     ptrtomethod ptr2 = (ptrtomethod) &fuu::bax;      base *f1 = new foo;     base *f2 = new fuu;      (f1->*ptr1)();     (f2->*ptr2)(); } 

it's worth noting reason target object contravariant because this parameter being passed function, , parameters are, in theory, contravariant (if function can use base*, can safely plugged algorithm provides derived* actual arguments).

however, arbitrary parameters, shim may needed adjust pointer, if base subobject not placed @ beginning of derived class layout. pointer-to-members, pointer adjustment this pointer built language. (and reason, pointer-to-member-of-class-with-virtual-inheritance can quite large)


Comments