Re: Casting of pointer to member functions
I would discourage using reinterpret_cast to cast between pointers of bas
and derived class. This may not work correctly when the pointers to the
derived class and its base object are different.
"David Olsson" <vonolsson@gmail.com> wrote in message
news:1158322911.471685.111790@b28g2000cwb.googlegroups.com...
I am writing an application in which I use pointer to member functions
to achieve a certain functionality. At one point I need to be able to
cast between different types of member function. In a very simplified
version, this is what I want to do:
class Base {
public:
typedef void (Base::*MethodPrototype)();
Base(MethodPrototype method): m_method(method) {}
void call() {
(this->*m_method)();
}
private:
MethodPrototype m_method;
};
class Derived: virtual public Base {
public:
Derived():
Base(reinterpret_cast<MethodPrototype>(&Derived::myMethod)) {}
int myMethod() {
return(1);
}
};
The constructor of the Derived class failes to compile as visual c++
reports that the reinterpret_cast is invalid. This does however only
occur when the inheritance is virtual, if it isn't virtual, the casting
works fine. Furthermore, the above code compiles with GCC 3.4.2. Is it
Visual C++ or GCC that isn't quite conformant. And is there a
workaround to be able to do this?
Thanks for any help!
/ David Olsson