Virtual Mem Func Ptr Call Fails When Base Class Has No Vtable

Martin v. Loewis
Mon Sep 13 23:45:00 GMT 1999

> The following causes various faults (I've seen SEGV, BUS, ILL) on my system. 
> If the function Sub::test is non-virtual, or Base contains some virtual
> function, all is fine:

Thanks for your bug report. The bug is in your code, however: Without
the cast

   BaseMemCb cb = (BaseMemCb) &Sub::test;

g++ says (correctly) In function `int main()': converting `void (Sub::*)()' to `void (Base::*)()' is a contravariance violation conversion to `void (Base::*)()' from `void (Sub::*)()' type `Sub' is not a base type for type `Base'    in pointer to member conversion

Please see your C++ book on why this cast is invalid.

Strictly speaking, this is a reinterpret_cast; using the pointer
results in undefined behaviour. g++ choses to crash the code, which is
conforming to the C++ standard.

Hope this helps,

More information about the Gcc-bugs mailing list